#!/bin/sh
# MobileHive headless installer for Raspberry Pi (and other Debian-style Linux on ARM).
#
#   curl -fsSL https://dl.mobilehive.io/install.sh | sudo bash
#
# Installs (or upgrades) `mhive` in /usr/local/bin, adb, the `mobilehive` service user, /etc/mobilehive,
# /var/lib/mobilehive and the systemd service, and starts it. Safe to run again: that is how you upgrade.
#
# Settings (environment):
#   MOBILEHIVE_VERSION   a version such as 0.1.0 (default: the latest)
#   MOBILEHIVE_BASE_URL  where releases live (default: https://dl.mobilehive.io)
#   MOBILEHIVE_NO_START  1: install and enable, but don't (re)start the service
set -eu

BASE_URL="${MOBILEHIVE_BASE_URL:-https://dl.mobilehive.io}"
VERSION="${MOBILEHIVE_VERSION:-latest}"
BIN=/usr/local/bin/mhive
UNIT=mobilehive

say() { printf '\033[1m==>\033[0m %s\n' "$*"; }
warn() { printf '\033[33mwarning:\033[0m %s\n' "$*" >&2; }
die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }

# ----- root --------------------------------------------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then
    # Run as a file (sh install.sh): ask sudo. Piped in: the script can't run itself again.
    if [ -f "$0" ] && [ -r "$0" ] && command -v sudo >/dev/null 2>&1; then
        exec sudo -E sh "$0" "$@"
    fi
    die "run it as root: curl -fsSL $BASE_URL/install.sh | sudo bash"
fi

# ----- system ------------------------------------------------------------------------------------------
[ "$(uname -s)" = "Linux" ] || die "mhive runs on Linux (this is $(uname -s))"
if ! command -v systemctl >/dev/null 2>&1 || [ ! -d /run/systemd/system ]; then
    die "this system does not run systemd; run 'mhive service run' under your own supervisor instead"
fi

# The userland decides, not the kernel: 32-bit Raspberry Pi OS on a Pi 4 or 5 runs a 64-bit kernel
# (uname says aarch64) with 32-bit programs.
arch=""
if command -v dpkg >/dev/null 2>&1; then
    arch="$(dpkg --print-architecture)"
fi
[ -n "$arch" ] || arch="$(uname -m)"
case "$arch" in
    arm64 | aarch64) TARGET=aarch64-unknown-linux-gnu ;;
    armhf | armv7l | armv8l) TARGET=armv7-unknown-linux-gnueabihf ;;
    armel | armv6l) die "ARMv6 (Raspberry Pi 1 and Zero) is not supported; a Pi 2 or newer is needed" ;;
    *) die "unsupported architecture: $arch (supported: 64-bit and 32-bit ARM Linux, armv7 or newer)" ;;
esac

if command -v curl >/dev/null 2>&1; then
    fetch() { curl -fsSL --retry 3 -o "$2" "$1"; }
elif command -v wget >/dev/null 2>&1; then
    fetch() { wget -q -O "$2" "$1"; }
else
    die "curl or wget is needed"
fi
command -v sha256sum >/dev/null 2>&1 || die "sha256sum is needed (coreutils)"

# ----- mhive -------------------------------------------------------------------------------------------
case "$VERSION" in
    latest) REL="latest" ;;
    v*) REL="$VERSION" ;;
    *) REL="v$VERSION" ;;
esac
NAME="mhive-$TARGET"
URL="$BASE_URL/releases/$REL/$NAME"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT INT TERM

say "Downloading $NAME ($REL)"
fetch "$URL" "$TMP/$NAME" || die "could not download $URL"
fetch "$URL.sha256" "$TMP/$NAME.sha256" || die "could not download $URL.sha256"
want="$(cut -d' ' -f1 <"$TMP/$NAME.sha256")"
got="$(sha256sum "$TMP/$NAME" | cut -d' ' -f1)"
[ -n "$want" ] && [ "$want" = "$got" ] || die "checksum mismatch for $NAME (expected $want, got $got)"
say "Checksum OK ($got)"

chmod 0755 "$TMP/$NAME"
"$TMP/$NAME" --version >/dev/null 2>&1 || die "the downloaded mhive does not run here (glibc 2.31 or newer is needed)"
new_version="$("$TMP/$NAME" --version | cut -d' ' -f2)"
old_version=""
if [ -x "$BIN" ]; then
    old_version="$("$BIN" --version 2>/dev/null | cut -d' ' -f2 || true)"
fi
# Next to the running one, then renamed over it: a running service keeps its file until it restarts.
install -m 0755 "$TMP/$NAME" "$BIN.new"
mv -f "$BIN.new" "$BIN"
if [ -n "$old_version" ]; then
    say "mhive $old_version -> $new_version in $BIN"
else
    say "mhive $new_version in $BIN"
fi

# ----- adb ---------------------------------------------------------------------------------------------
if command -v adb >/dev/null 2>&1; then
    say "adb is installed ($(command -v adb))"
elif command -v apt-get >/dev/null 2>&1; then
    say "Installing adb"
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -qq
    # Debian 12 / Pi OS Bookworm call it adb; older releases android-tools-adb. Both bring the udev rules that
    # let the plugdev group open USB phones.
    apt-get install -y -qq adb >/dev/null 2>&1 || apt-get install -y -qq android-tools-adb >/dev/null \
        || die "could not install adb with apt"
else
    warn "no apt-get here: install adb yourself (or set [adb] path in /etc/mobilehive/config.toml)"
fi

# ----- service -----------------------------------------------------------------------------------------
# USB phones are opened through the plugdev group (udev rules from the adb package).
getent group plugdev >/dev/null 2>&1 || groupadd --system plugdev
was_active=0
systemctl is-active --quiet "$UNIT" && was_active=1

# The service user, /etc/mobilehive, /var/lib/mobilehive and the unit: mhive writes them itself.
say "Setting up the service"
"$BIN" service install --no-start
if id -nG mobilehive 2>/dev/null | tr ' ' '\n' | grep -qx plugdev; then :; else
    usermod -a -G plugdev mobilehive
fi

if [ "${MOBILEHIVE_NO_START:-0}" = "1" ]; then
    say "Enabled; not started (MOBILEHIVE_NO_START=1)"
elif [ "$was_active" = "1" ]; then
    say "Restarting the service"
    systemctl restart "$UNIT"
else
    say "Starting the service"
    systemctl start "$UNIT"
fi

# ----- next steps --------------------------------------------------------------------------------------
key_state="$(MOBILEHIVE_CONFIG_DIR=/etc/mobilehive MOBILEHIVE_DATA_DIR=/var/lib/mobilehive "$BIN" secrets list 2>/dev/null | sed -n 's/^liquid-api-key *//p' || true)"
host="$(hostname 2>/dev/null || echo raspberrypi)"

cat <<EOF

MobileHive $new_version is installed and the service is $(systemctl is-active "$UNIT" 2>/dev/null || echo "not running").

Next steps:
EOF
step=1
if [ "$key_state" != "set" ]; then
    echo "  $step. Add your Liquid API key:    sudo mhive secrets set liquid"
    step=$((step + 1))
fi
cat <<EOF
  $step. Plug in your Android phone (USB debugging on), then allow this Pi on the phone:
       sudo -u mobilehive mhive devices
  $((step + 1)). From your Mac, copy your workflows over:
       rsync -a --delete --rsync-path="sudo -u mobilehive rsync" \\
         ~/Library/Application\\ Support/com.yonnic.mobilehive/{workflows,recordings} $host:/var/lib/mobilehive/
  $((step + 2)). Check it:     mhive status        mhive schedule list
     Its log:      journalctl -u $UNIT -f

Upgrade later by running the same command again.
EOF
