#!/bin/sh
# hamctl installer — downloads the right prebuilt binary for this machine, sets up a
# home, and (interactively) configures a password / service / systemd unit.
#
#   curl -fsSL https://hamctl.monocul.us/install.sh | sh
#
# Env overrides:
#   PREFIX=/usr/local/bin     where the binary goes
#   HAMCTL_HOME=/opt/hamctl   config + manifests home (default: root→/opt/hamctl else ~/.hamctl)
#   HAMCTL_BASE=https://...   download base URL
#   HAMCTL_NONINTERACTIVE=1   skip all prompts (print next steps instead)
set -eu

BASE="${HAMCTL_BASE:-https://hamctl.monocul.us}"
PREFIX="${PREFIX:-/usr/local/bin}"

# ---- platform detection -------------------------------------------------------
[ "$(uname -s)" = "Linux" ] || { echo "hamctl ships Linux binaries only (this is $(uname -s))." >&2; exit 1; }
m=$(uname -m)
case "$m" in
    x86_64 | amd64)  arch=x86_64 ;;
    aarch64 | arm64) arch=aarch64 ;;
    armv7l)          arch=armv7 ;;
    armv6l)          arch=armv6 ;;
    i686 | i386)     arch=i386 ;;
    riscv64)         arch=riscv64 ;;
    *) echo "no prebuilt hamctl for architecture: $m" >&2; exit 1 ;;
esac
file="hamctl-linux-$arch"

# ---- home + privilege ---------------------------------------------------------
if [ -n "${HAMCTL_HOME:-}" ]; then HOME_DIR="$HAMCTL_HOME"
elif [ "$(id -u)" = "0" ]; then    HOME_DIR="/opt/hamctl"
else                                HOME_DIR="$HOME/.hamctl"; fi

fetch() {  # fetch <url> <outfile|->
    if command -v curl >/dev/null 2>&1; then curl -fSL "$1" -o "$2"
    elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
    else echo "need curl or wget" >&2; exit 1; fi
}
sha256() {  # sha256 <file> -> hash
    if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'
    elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'; fi
}
ask() {  # ask "<prompt>" <default: Y|N> ; returns 0 on yes
    [ -e /dev/tty ] && [ -z "${HAMCTL_NONINTERACTIVE:-}" ] || return 1
    printf '%s ' "$1" > /dev/tty
    read -r a < /dev/tty || a=""
    [ -z "$a" ] && a="$2"
    case "$a" in [Yy]*) return 0 ;; *) return 1 ;; esac
}

run_priv() {  # run as root when possible
    if [ "$(id -u)" = "0" ]; then "$@"; else sudo "$@"; fi
}

# ---- download + verify --------------------------------------------------------
url="$BASE/bin/$file"
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
echo "Downloading $url"
fetch "$url" "$tmp"

want=""
sums=$(fetch "$BASE/bin/SHA256SUMS" - 2>/dev/null || true)
if [ -n "$sums" ]; then
    want=$(printf '%s\n' "$sums" | awk -v f="$file" '($2==f)||($2=="*"f){print $1}')
    got=$(sha256 "$tmp")
    if [ -n "$want" ] && [ -n "$got" ] && [ "$want" != "$got" ]; then
        echo "checksum mismatch for $file" >&2; exit 1
    fi
    [ -n "$want" ] && echo "checksum OK"
fi

# ---- install / update in place ------------------------------------------------
dest="$PREFIX/hamctl"
chmod +x "$tmp"
if [ -f "$dest" ] && [ -n "$want" ] && [ "$(sha256 "$dest")" = "$want" ]; then
    echo "hamctl is already up to date ($arch); skipping binary replace."
    rm -f "$tmp"; trap - EXIT
else
    action="Installing"; [ -f "$dest" ] && action="Updating"
    echo "$action $dest"
    if [ -w "$PREFIX" ] || [ "$(id -u)" = "0" ]; then mv "$tmp" "$dest"; else run_priv mv "$tmp" "$dest"; fi
    trap - EXIT
fi
BIN="$dest"

# ---- home setup / upgrade -----------------------------------------------------
if [ -f "$HOME_DIR/hamctl.toml" ]; then
    "$BIN" upgrade --home "$HOME_DIR"
else
    "$BIN" init --home "$HOME_DIR"
fi
cfg="$HOME_DIR/hamctl.toml"

# ---- first-run: password ------------------------------------------------------
if grep -q '^password_hash = ""' "$cfg" 2>/dev/null; then
    if ask "Set the admin password now? [Y/n]" Y; then
        "$BIN" set-password --home "$HOME_DIR" < /dev/tty
    else
        echo "  → set it later with:  $BIN set-password --home $HOME_DIR"
    fi
fi

# ---- first-run: install AFRN --------------------------------------------------
if ask "Install the AFRN client now? [y/N]" N; then
    "$BIN" install afrn --home "$HOME_DIR" --arch "$arch" || echo "  (AFRN install failed; you can retry later)"
fi

# ---- first-run: systemd service ----------------------------------------------
unit="/etc/systemd/system/hamctl.service"
if command -v systemctl >/dev/null 2>&1 && [ ! -f "$unit" ]; then
    if ask "Install a systemd service so hamctl starts on boot? [Y/n]" Y; then
        tmpunit=$(mktemp)
        cat > "$tmpunit" <<UNIT
[Unit]
Description=hamctl web UI
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=$BIN --config $cfg
WorkingDirectory=$HOME_DIR
Restart=always
RestartSec=2

[Install]
WantedBy=multi-user.target
UNIT
        run_priv mv "$tmpunit" "$unit"
        run_priv systemctl daemon-reload
        run_priv systemctl enable --now hamctl.service
        echo "  → systemd service 'hamctl' enabled."
    fi
fi

echo
echo "hamctl ($arch) installed → $BIN"
echo "  home:   $HOME_DIR"
echo "  config: $cfg"
if ! command -v systemctl >/dev/null 2>&1 || [ ! -f "$unit" ]; then
    echo "  start:  $BIN --config $cfg     # serves the web UI on :8080"
fi
