#!/usr/bin/env bash
# Version-pinned installer. Review this file before running it with elevated privileges.
# Keep all work inside main: an interrupted curl | bash must not run a partial download.
set -euo pipefail

# Replaced in the marketing build when MINIPILOT_DOWNLOAD_BASE_URL is configured.
RELEASE_BASE_URL="https://mini-pilot-marketing.pages.dev/downloads"

fail() { echo "MiniPilot: $*" >&2; exit 1; }
usage() {
  echo 'Usage: bash install.sh  # automatically choose the Ubuntu package'
  echo '   or: bash install.sh ./minipilot_VERSION_ARCH.deb'
  echo '   or: bash install.sh --url https://HOST/package.deb --sha256 TRUSTED_SHA256'
}
cleanup() { [[ -z ${tmp:-} ]] || rm -rf -- "$tmp"; }

main() {
  if [[ ${1:-} == --help || ${1:-} == -h ]]; then usage; return; fi
  [[ $(uname -s) == Linux && -r /etc/os-release ]] || fail 'Requires Ubuntu Linux.'
  source /etc/os-release
  [[ ${ID:-} == ubuntu ]] || fail 'Requires Ubuntu (not a derivative or Debian).'
  local sha architecture package url version
  case "${VERSION_ID:-}" in
    22.04) sha=d10a4275525db450da58f5281629a45a5ac30093ff40576d389fb08854c84aff ;;
    24.04) sha=7731ce662c62543a55eac764f7532be851ac0e9a544734f370797397497b059e ;;
    26.04) sha=8e2ab520a5596e2df17fef10031a20802671d9dfe8e4193d618a49061ea5fa31 ;;
    *) fail 'Supported releases: Ubuntu 22.04, 24.04 and 26.04 LTS.' ;;
  esac
  architecture=$(dpkg --print-architecture)
  [[ $architecture == amd64 ]] || fail "No qualified package for $architecture. Intel/AMD x86-64 (amd64) is required."
  [[ -d /run/systemd/system ]] || fail 'Boot Ubuntu with systemd before installing MiniPilot.'
  tmp=''
  trap cleanup EXIT
  if [[ $# == 0 ]]; then
    [[ $RELEASE_BASE_URL != *example.invalid* ]] || fail 'Public downloads are not configured yet. Use the downloaded .deb or the --url/--sha256 options.'
    url="${RELEASE_BASE_URL}/minipilot_0.2.0-4+ubuntu${VERSION_ID}_amd64.deb"
  elif [[ $# == 4 && $1 == --url && $3 == --sha256 ]]; then
    url=$2
    sha=$4
  elif [[ $# == 1 && -f $1 && $1 == *.deb ]]; then
    package=$(realpath -- "$1")
    url=''
  else
    usage
    return 1
  fi
  if [[ -n $url ]]; then
    [[ $url == https://* && $url != *$'\n'* ]] || fail 'Downloads require HTTPS.'
    [[ $sha =~ ^[[:xdigit:]]{64}$ ]] || fail 'Supply a trusted SHA-256 checksum.'
    command -v curl >/dev/null || fail 'Install curl first: sudo apt-get update && sudo apt-get install -y curl ca-certificates'
    tmp=$(mktemp -d)
    chmod 755 "$tmp"
    package="$tmp/minipilot.deb"
    echo "Downloading MiniPilot 0.2.0 for Ubuntu $VERSION_ID ($architecture)..."
    curl --fail --location --proto '=https' --proto-redir '=https' --retry 2 --connect-timeout 15 --max-time 600 --output "$package" "$url" || fail 'Download failed. Nothing installed; check internet access and release availability.'
    printf '%s  %s\n' "$sha" "$package" | sha256sum --check --status || fail 'Checksum mismatch. Nothing installed.'
    chmod 644 "$package"
  fi
  [[ $(dpkg-deb -f "$package" Package) == minipilot ]] || fail 'This is not a MiniPilot package.'
  [[ $(dpkg-deb -f "$package" X-MiniPilot-Ubuntu) == "$VERSION_ID" ]] || fail 'Package Ubuntu version mismatch.'
  [[ $(dpkg-deb -f "$package" Architecture) == "$architecture" ]] || fail 'Package CPU architecture mismatch.'
  version=$(dpkg-deb -f "$package" Version)
  local -a elevate=()
  if [[ $(id -u) != 0 ]]; then
    command -v sudo >/dev/null || fail 'Run with an administrator account that has sudo.'
    sudo -v || fail 'Administrator authorization cancelled. Nothing installed.'
    elevate=(sudo)
  fi
  echo "Installing $version. APT will install required system dependencies."
  "${elevate[@]}" apt-get update
  "${elevate[@]}" apt-get install -y "$package"
  echo
  echo 'MiniPilot installed. Configuration and deliberately disabled sockets are preserved on upgrades.'
  if systemctl --quiet is-active minipilot.socket && systemctl --quiet is-active minipilot-auth.socket; then
    echo 'Startup: systemd sockets are active; the web service starts on first connection.'
  else
    echo 'Sockets are inactive. Inspect: systemctl status minipilot.socket minipilot-auth.socket'
    echo 'To enable startup intentionally: sudo systemctl enable --now minipilot-auth.socket minipilot.socket'
  fi
  echo 'Terminal: minipilot'
  echo 'Browser address: minipilot web'
  echo 'Local mode: http://127.0.0.1:8765 — sign in with your Ubuntu username/password.'
  echo 'From a laptop: ssh -N -L 127.0.0.1:8765:127.0.0.1:8765 USER@SERVER'
  echo 'Then open http://127.0.0.1:8765 on the laptop. HTTPS tunnel domains use your Ubuntu login; no Cloudflare Access setup is required.'
  echo 'GPU drivers, Docker/Podman and Cloudflare tunnels are optional and remain under your control.'
}

main "$@"
