#!/bin/sh
# Install Adom Hydrogen on Linux.
#
#   sh install-linux.sh [options]
#
# Picks the package for this system from /etc/os-release:
#   Debian, Ubuntu and their family  -> the .deb, installed with apt
#   Fedora, RHEL, openSUSE family    -> the .rpm, installed with dnf, or zypper on openSUSE
#   anything else                    -> the AppImage, in ~/.local/bin, with a menu entry
# Every download is checked against its published sha256 (Hydrogen's update manifest, or the
# release's own file list with --version) before it is used.
# sudo is used only for the system package install (apt/dnf/zypper), and the script says so first;
# the AppImage path never needs it.
#
# Options:
#   --kind deb|rpm|appimage   install this kind instead of the detected one
#   --manifest URL            read this manifest instead of the public one
#   --insiders                install the insiders build. Signs you in to Adom the way Hydrogen
#                             does (your browser opens the Adom sign-in; approve it there), unless
#                             Hydrogen on this computer is already signed in or ADOM_TOKEN is set.
#                             The sign-in is then saved for Hydrogen, so it starts signed in.
#   --version X.Y.Z           install that release, without a manifest or a sign-in: the files and
#                             their sha256 come from the release's own list on the Adom wiki
#   --dry-run                 show what would be done, download and verify, install nothing
set -eu

PUBLIC_MANIFEST="https://wiki.adom.inc/api/v1/pages/hydrogen/files/version.json"
INSIDERS_MANIFEST="https://wiki.adom.inc/api/v1/pages/adom/insiders/files/hydrogen/version.json"
MANIFEST="${HYDROGEN_MANIFEST_URL:-$PUBLIC_MANIFEST}"
KIND=""
DRY=0
TIER="public"
RELEASE=""
UA="adom-hydrogen-installer/1"
SESSION_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/hydrogen-desktop/hydrogen-session.txt"

say() { printf '%s\n' "Hydrogen installer: $*"; }
die() { printf '%s\n' "Hydrogen installer: $*" >&2; exit 1; }

# Run a package install, waiting out another package manager that holds the lock (Fedora's own
# updates run right after boot): up to 5 minutes, saying so, then a clear failure.
pkg_install() {
  tries=0
  while :; do
    : > "$TMP/pkg.rc"
    # `|| rc=$?` keeps set -e from ending the group before the exit code is written.
    { rc=0; "$@" 2>&1 || rc=$?; echo "$rc" > "$TMP/pkg.rc"; } | tee "$TMP/pkg.log"
    [ "$(cat "$TMP/pkg.rc")" = 0 ] && return 0
    if grep -qiE 'could not get lock|unable to acquire the dpkg frontend lock|rpm transaction lock|another transaction is in progress|system management is locked' "$TMP/pkg.log"; then
      tries=$((tries + 1))
      [ "$tries" -le 30 ] || die "another program is still installing software on this computer (the system updater, most likely) after 5 minutes. Let it finish, then run this again. Nothing was installed."
      say "another program is installing software right now (the system updater, most likely); waiting for it to finish, then trying again ($tries of 30)."
      sleep 10
      continue
    fi
    die "the package install failed (see the lines above). Nothing else was changed."
  done
}

while [ $# -gt 0 ]; do
  case "$1" in
    --kind) KIND="${2:-}"; shift 2 ;;
    --kind=*) KIND="${1#--kind=}"; shift ;;
    --manifest) MANIFEST="${2:-}"; shift 2 ;;
    --manifest=*) MANIFEST="${1#--manifest=}"; shift ;;
    --insiders) MANIFEST="$INSIDERS_MANIFEST"; TIER="insiders"; shift ;;
    --version) RELEASE="${2:-}"; shift 2 ;;
    --version=*) RELEASE="${1#--version=}"; shift ;;
    --dry-run) DRY=1; shift ;;
    -h|--help) sed -n '2,/^[^#]/p' "$0" 2>/dev/null | sed '$d' | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) die "unknown option: $1 (try --help)" ;;
  esac
done

[ "$(uname -s)" = "Linux" ] || die "this installer is for Linux."
case "$(uname -m)" in
  x86_64|amd64) ARCH=x64 ;;
  *) die "Hydrogen for Linux is built for x86_64 only; this machine is $(uname -m)." ;;
esac
for t in curl sha256sum python3; do
  command -v "$t" >/dev/null 2>&1 || die "needs '$t'; install it with your package manager and run this again."
done

# ── Which package fits this system ───────────────────────────────────────────────────────────
ID=""; ID_LIKE=""; PRETTY_NAME="this system"
if [ -r /etc/os-release ]; then
  # shellcheck disable=SC1091
  . /etc/os-release
fi
family="$(printf '%s %s' "$ID" "$ID_LIKE" | tr 'A-Z' 'a-z')"
PKGTOOL=""
if [ -z "$KIND" ]; then
  case " $family " in
    *" debian "*|*" ubuntu "*) KIND=deb ;;
    *" fedora "*|*" rhel "*|*" centos "*|*" suse "*|*" opensuse "*|*" sles "*) KIND=rpm ;;
    *) KIND=appimage ;;
  esac
fi
case "$KIND" in
  deb) command -v apt-get >/dev/null 2>&1 && PKGTOOL=apt || { say "no apt on $PRETTY_NAME, using the AppImage instead."; KIND=appimage; } ;;
  rpm)
    if command -v dnf >/dev/null 2>&1; then PKGTOOL=dnf
    elif command -v zypper >/dev/null 2>&1; then PKGTOOL=zypper
    else say "no dnf or zypper on $PRETTY_NAME, using the AppImage instead."; KIND=appimage; fi ;;
  appimage) ;;
  *) die "--kind must be deb, rpm or appimage" ;;
esac
say "$PRETTY_NAME: installing the $KIND package${PKGTOOL:+ with $PKGTOOL}."

# ── Adom sign-in for the insiders build (the same flow as Hydrogen's own) ────────────────────
# Prints the session token on stdout for the caller to capture; everything else goes to stderr.
# Nothing secret is ever on a command line: python does the HTTP itself, and the sign-in link
# (whoever holds it can collect the session once it is approved) is printed only when no browser
# could be opened, so it does not end up on someone's screen or in a recording.
adom_signin() {
  python3 - "$UA" <<'PY'
import json, os, subprocess, sys, time, urllib.request, urllib.error
UA = sys.argv[1]
def call(method, url, body=None):
    req = urllib.request.Request(url, data=None if body is None else json.dumps(body).encode(), method=method,
        headers={"User-Agent": UA, "Content-Type": "application/json", "Accept": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r: return r.status, json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        return e.code, {}
    except Exception:
        return 0, {}
def say(m): print("Hydrogen installer: " + m, file=sys.stderr, flush=True)
code, d = call("POST", "https://carbon.adom.inc/auth/intents", {"max_age": 7776000})
tok = d.get("token") if 200 <= code < 300 else None
if not tok: say("could not start the Adom sign-in (no connection to Adom?)."); sys.exit(1)
url = (d.get("auth_url") or "https://hydrogen.adom.inc/auth/intent?token=" + tok)
url += ("&" if "?" in url else "?") + "app=linux&app_version=installer"
opened = False
if os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"):
    for opener in ("xdg-open", "gio", "sensible-browser"):
        args = [opener, "open", url] if opener == "gio" else [opener, url]
        try:
            subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True); opened = True; break
        except OSError:
            continue
if opened:
    say("your browser is opening the Adom sign-in. Sign in there and press Approve; this window carries on by itself.")
else:
    say("no browser could be opened here. Open this link on this computer, sign in and press Approve:")
    print("    " + url, file=sys.stderr, flush=True)
deadline = time.time() + 15 * 60
while time.time() < deadline:
    time.sleep(2)
    code, s = call("GET", "https://carbon.adom.inc/auth/intents/%s/status" % tok)
    if code == 410: break
    if s.get("state") == "authenticated" and s.get("session_token"):
        say("signed in to Adom."); print(s["session_token"]); sys.exit(0)
say("the sign-in link expired before it was approved. Run this again to get a fresh one."); sys.exit(1)
PY
}

# ── What to install: a named release, or the manifest of your tier ───────────────────────────
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT INT TERM
if [ -n "$RELEASE" ]; then
  case "$RELEASE" in *[!0-9.]*|"") die "--version takes a release number like 1.0.712" ;; esac
  # The release's own asset list (public, with each file's sha256), no manifest, no sign-in.
  curl -fsSL -A "$UA" "https://wiki.adom.inc/api/v1/packages/adom/hydrogen/$RELEASE/assets" -o "$TMP/assets.json" \
    || die "could not read release $RELEASE (is the number right?)."
  TIER="release $RELEASE"
  python3 -c 'import json,sys; sys.exit(0 if json.load(open(sys.argv[1])).get("assets") else 1)' "$TMP/assets.json" \
    || die "there is no Hydrogen release $RELEASE (check the number on the Adom Hydrogen page)."
  ENTRY="$(python3 - "$TMP/assets.json" "$KIND" "$RELEASE" <<'PY'
import json, sys
d = json.load(open(sys.argv[1])); kind, ver = sys.argv[2], sys.argv[3]
ext = {"deb": ".deb", "rpm": ".rpm", "appimage": ".AppImage"}[kind]
import re
# A release can carry a later build of its Linux packages (1.0.712-2): take the highest revision.
def rev(n):
    m = re.search(re.escape(ver) + r"-(\d+)", n)
    return int(m.group(1)) if m else 0
best = None
for a in d.get("assets", []):
    n = str(a.get("filename") or "")
    if a.get("platform") == "linux" and n.endswith(ext) and a.get("sha256"):
        if best is None or rev(n) > rev(best[0]): best = (n, a["sha256"].lower())
if best:
    print("https://wiki.adom.inc/download/adom/hydrogen/%s/%s" % (ver, best[0]), best[1], best[0], ver)
PY
)"
else
  if [ "$TIER" = "insiders" ]; then
    # Who is asking: ADOM_TOKEN, else this computer's Hydrogen sign-in, else sign in now.
    SAVE_SESSION=0
    if [ -n "${ADOM_TOKEN:-}" ]; then TOKEN="$ADOM_TOKEN"
    elif [ -s "$SESSION_FILE" ]; then TOKEN="$(cat "$SESSION_FILE")"; say "using the Adom sign-in Hydrogen already has on this computer."
    else TOKEN="$(adom_signin)" || die "not signed in, nothing installed."; SAVE_SESSION=1
    fi
    # The token reaches curl through a config on stdin (printf is a shell builtin), never on a
    # command line, where any local user could read it in the process list (F103).
    printf 'header = "Authorization: Bearer %s"\n' "$TOKEN" | curl -fsSL -A "$UA" -K - "$MANIFEST" -o "$TMP/version.json" \
      || die "this Adom account cannot see the insiders build (it is not on the insiders list). Nothing installed. Without --insiders you get the public release."
    if [ "$SAVE_SESSION" = 1 ] && [ "$DRY" = 0 ] && [ ! -e "$SESSION_FILE" ]; then
      # Hand the sign-in to Hydrogen, so it starts signed in instead of asking again.
      ( umask 077; mkdir -p "$(dirname "$SESSION_FILE")"; printf '%s' "$TOKEN" > "$SESSION_FILE" )
      say "saved the sign-in for Hydrogen (it starts signed in)."
    fi
    TOKEN=""
  else
    curl -fsSL -A "$UA" "$MANIFEST" -o "$TMP/version.json" || die "could not read $MANIFEST"
  fi
  # url sha256 filename version, or nothing when this kind is not published.
  ENTRY="$(python3 - "$TMP/version.json" "$KIND" <<'PY'
import json, sys
m = json.load(open(sys.argv[1]))
e = (m.get("linux") or {}).get(sys.argv[2]) or {}
if e.get("installer_url") and e.get("installer_sha256"):
    name = e.get("installer_filename") or e["installer_url"].rsplit("/", 1)[-1]
    print(e["installer_url"], e["installer_sha256"].lower(), name, m.get("version", "?"))
PY
)"
fi
[ -n "$ENTRY" ] || die "Hydrogen's $KIND package is not published in the $TIER build yet. (Try --kind appimage, or --insiders if you are an insider.)"
# shellcheck disable=SC2086
set -- $ENTRY
URL="$1"; SHA="$2"; NAME="$3"; VER="$4"
case "$NAME" in */*|..*|"") die "the manifest names an unsafe file: $NAME" ;; esac
say "Hydrogen $VER ($TIER): $NAME"

# ── Download and verify ──────────────────────────────────────────────────────────────────────
curl -fL --progress-bar "$URL" -o "$TMP/$NAME" || die "download failed: $URL"
GOT="$(sha256sum "$TMP/$NAME" | cut -d' ' -f1)"
[ "$GOT" = "$SHA" ] || die "the download does not match its published sha256 (got $GOT, expected $SHA). Nothing was installed."
say "sha256 verified."

if [ "$DRY" = 1 ]; then
  say "dry run: would install $NAME${PKGTOOL:+ with $PKGTOOL}. Nothing installed."
  exit 0
fi

# ── Install ──────────────────────────────────────────────────────────────────────────────────
SUDO=""
need_root() {
  if [ "$(id -u)" -eq 0 ]; then SUDO=""; return; fi
  command -v sudo >/dev/null 2>&1 || die "installing a system package needs root, and sudo is not available. Run this as root, or use --kind appimage."
  say "sudo is needed for one step: $1. You may be asked for your password."
  SUDO="sudo"
}
# Ralph F125: is the build in this package the one now installed? rpm: the package header's own
# digest and build time against the installed package's (Hydrogen's rpms carry no SIGMD5). deb:
# the program's checksum in the package's md5sums against the installed one.
RPM_STAMP='%{SHA1HEADER} %{BUILDTIME}'
same_build_rpm() {
  want="$(rpm -qp --qf "$RPM_STAMP" "$1" 2>/dev/null)"; have="$(rpm -q --qf "$RPM_STAMP" adom-hydrogen 2>/dev/null)"
  [ -n "$want" ] && [ "$want" = "$have" ]
}
same_build_deb() {
  want="$(dpkg-deb -I "$1" md5sums 2>/dev/null | awk '$2=="usr/bin/adom-hydrogen"{print $1}')"
  [ -n "$want" ] || return 0   # no md5sums in the package: nothing to compare against
  have="$(md5sum /usr/bin/adom-hydrogen 2>/dev/null | cut -d' ' -f1)"
  [ "$want" = "$have" ]
}
case "$KIND" in
  deb)
    need_root "apt installs the .deb system-wide (it puts adom-hydrogen in /usr/bin and the workspace helper in /usr/libexec)"
    # A path with ./ makes apt treat it as a local file and pull its dependencies.
    cp "$TMP/$NAME" "$TMP/hydrogen.deb"; chmod 644 "$TMP/hydrogen.deb"; chmod 755 "$TMP"
    pkg_install $SUDO apt-get install -y "$TMP/hydrogen.deb"
    # Ralph F125: a newer build of the SAME version can be left alone by the package manager.
    # Compare the program in the package with the one now installed, and reinstall if they differ.
    if ! same_build_deb "$TMP/hydrogen.deb"; then
      say "the package manager kept the build that was already installed (same version number); reinstalling this build."
      pkg_install $SUDO apt-get install -y --reinstall "$TMP/hydrogen.deb"
      same_build_deb "$TMP/hydrogen.deb" || die "the new build of $VER did not replace the installed one (the package manager kept the old files). Run: sudo apt-get install --reinstall $TMP/hydrogen.deb"
    fi
    BIN=/usr/bin/adom-hydrogen ;;
  rpm)
    need_root "$PKGTOOL installs the .rpm system-wide (it puts adom-hydrogen in /usr/bin and the workspace helper in /usr/libexec)"
    chmod 644 "$TMP/$NAME"; chmod 755 "$TMP"
    if [ "$PKGTOOL" = dnf ]; then pkg_install $SUDO dnf install -y "$TMP/$NAME"
    else pkg_install $SUDO zypper --non-interactive install --allow-unsigned-rpm "$TMP/$NAME"; fi
    # Ralph F125: dnf answers "Nothing to do" (and exit 0) for a newer build of the same version.
    if ! same_build_rpm "$TMP/$NAME"; then
      say "the package manager kept the build that was already installed (same version number); reinstalling this build."
      if [ "$PKGTOOL" = dnf ]; then pkg_install $SUDO dnf reinstall -y "$TMP/$NAME"
      else pkg_install $SUDO zypper --non-interactive install --force --allow-unsigned-rpm "$TMP/$NAME"; fi
      same_build_rpm "$TMP/$NAME" || die "the new build of $VER did not replace the installed one (the package manager kept the old files). Run: sudo $PKGTOOL reinstall $TMP/$NAME"
    fi
    BIN=/usr/bin/adom-hydrogen ;;
  appimage)
    DEST="$HOME/.local/bin"; mkdir -p "$DEST"
    install -m 755 "$TMP/$NAME" "$DEST/Adom-Hydrogen.AppImage"
    BIN="$DEST/Adom-Hydrogen.AppImage"
    APPS="${XDG_DATA_HOME:-$HOME/.local/share}/applications"; mkdir -p "$APPS"
    # The menu entry is named for Hydrogen's app id (Ralph F108): the desktop portal can then name
    # Hydrogen in its prompts (GNOME's screenshot permission), for a launch from the menu and after
    # an in-app update alike. Older installs named it adom-hydrogen.desktop.
    rm -f "$APPS/adom-hydrogen.desktop"
    cat > "$APPS/inc.adom.hydrogen-desktop.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=Adom Hydrogen
Comment=Adom Hydrogen, the AI workspace for hardware
Exec=$BIN %U
Icon=adom-hydrogen
Terminal=false
Categories=Development;IDE;Electronics;
StartupWMClass=adom-hydrogen
EOF
    command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$APPS" >/dev/null 2>&1 || true
    case ":$PATH:" in *":$DEST:"*) ;; *) say "note: $DEST is not on your PATH; the menu entry works either way." ;; esac
    say "the AppImage asks once for your password at its first start, to set up the workspace helper." ;;
esac

say "installed Hydrogen $VER. Start it from your apps menu (Adom Hydrogen) or run: $BIN"
