#!/bin/sh
# DeepLink headless host installer (Linux). Remote edition; remote terminal only.
#   curl -fsSL https://deeplinkai.cloud/download/deeplink-host/install.sh | sudo sh -s -- --expect-wallet 0xYOUR_WALLET
# Installs /usr/local/bin/deeplink-host, a systemd service running as YOUR user (never root), and prints a pairing
# code. Enter the code at https://web.deeplinkgame.com/pair with the same wallet. Any extra arguments are passed to
# "deeplink-host install" (see "deeplink-host install -h").
set -eu
BASE="${DEEPLINK_HOST_BASE:-https://deeplinkai.cloud/download/deeplink-host}"
VERSION="0.2.1"
die() { echo "deeplink-host install: $*" >&2; exit 1; }
[ "$(uname -s)" = "Linux" ] || die "only Linux is supported by this script (macOS: coming later)"
[ "$(id -u)" = "0" ] || die "run with sudo: curl -fsSL $BASE/install.sh | sudo sh -s -- --expect-wallet 0xYOUR_WALLET"
command -v systemctl >/dev/null 2>&1 || die "systemd is required"
case "$(uname -m)" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) die "unsupported CPU $(uname -m) (amd64 and arm64 only)" ;;
esac
TARGET_USER="${DEEPLINK_USER:-${SUDO_USER:-}}"
[ -n "$TARGET_USER" ] && [ "$TARGET_USER" != "root" ] || die "run via sudo from your normal account, or set DEEPLINK_USER=<user>; the host never runs as root"
id "$TARGET_USER" >/dev/null 2>&1 || die "no such user: $TARGET_USER"
case " $* " in *" --expect-wallet "*) ;; *) echo "note: add --expect-wallet 0xYOUR_WALLET so only your wallet can pair this machine" >&2 ;; esac
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
NAME="deeplink-host-$VERSION-linux-$ARCH"
fetch() { if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"; else wget -qO "$2" "$1"; fi; }
fetch "$BASE/$NAME" "$TMP/deeplink-host" || die "download failed: $BASE/$NAME"
fetch "$BASE/SHA256SUMS" "$TMP/SHA256SUMS" || die "download failed: $BASE/SHA256SUMS"
WANT="$(grep " $NAME\$" "$TMP/SHA256SUMS" | cut -d' ' -f1)"
GOT="$(sha256sum "$TMP/deeplink-host" | cut -d' ' -f1)"
[ -n "$WANT" ] && [ "$WANT" = "$GOT" ] || die "checksum mismatch for $NAME"
if systemctl is-active --quiet deeplink-host 2>/dev/null; then systemctl stop deeplink-host; fi
install -m 0755 "$TMP/deeplink-host" /usr/local/bin/deeplink-host
echo "installed /usr/local/bin/deeplink-host $VERSION for user $TARGET_USER" >&2
exec /usr/local/bin/deeplink-host install --user "$TARGET_USER" --enable "$@"
