#!/usr/bin/env sh
# AMerc Outpost standalone installer 1.1.45-overair
set -eu

AMERC_BASE=${AMERC_BASE_URL:-https://amerc.ai}
INSTALL_ROOT=${AMERC_OUTPOST_HOME:-"$HOME/.local/share/amerc/outpost"}

printf 'AMerc account username: '
IFS= read -r amerc_user
printf 'AMerc account password: '
stty -echo 2>/dev/null || true
IFS= read -r amerc_password
stty echo 2>/dev/null || true
printf '\nLocal API username [admin]: '
IFS= read -r local_user
local_user=${local_user:-admin}
printf 'Local API password [123456]: '
stty -echo 2>/dev/null || true
IFS= read -r local_password
stty echo 2>/dev/null || true
local_password=${local_password:-123456}
printf '\n'

cookie_file=$(mktemp "${TMPDIR:-/tmp}/amerc-outpost-cookie.XXXXXX")
package_file=$(mktemp "${TMPDIR:-/tmp}/amerc-outpost.XXXXXX.tar.gz")
cleanup() { rm -f "$cookie_file" "$package_file"; }
trap cleanup EXIT HUP INT TERM

curl -fsS -L -c "$cookie_file" -b "$cookie_file" -o /dev/null \
  --data-urlencode "username=$amerc_user" \
  --data-urlencode "password=$amerc_password" \
  "$AMERC_BASE/login"

build=$(curl -fsS -b "$cookie_file" \
  --data-urlencode 'platform=linux' \
  --data-urlencode "label=$(hostname)-outpost" \
  --data-urlencode 'servesAgents=true' \
  --data-urlencode "localUsername=$local_user" \
  --data-urlencode "localPassword=$local_password" \
  "$AMERC_BASE/api/outposts/build")
download_url=$(printf '%s' "$build" | sed -n 's/.*"downloadUrl":"\([^"]*\)".*/\1/p')
case "$download_url" in
  http://*|https://*) : ;;
  /*) download_url="$AMERC_BASE$download_url" ;;
  *) printf 'AMerc did not approve the Outpost download.\n' >&2; exit 1 ;;
esac

curl -fsS -L -o "$package_file" "$download_url"
mkdir -p "$INSTALL_ROOT" "$INSTALL_ROOT/logs"
tar -xzf "$package_file" -C "$INSTALL_ROOT"
chmod 700 "$INSTALL_ROOT/run-outpost.sh" "$INSTALL_ROOT/outpost-cli.sh" "$INSTALL_ROOT/outpost.mjs" 2>/dev/null || true
mkdir -p "$HOME/.local/bin"
ln -sf "$INSTALL_ROOT/outpost-cli.sh" "$HOME/.local/bin/amerc-outpost"
ln -sf "$INSTALL_ROOT/outpost-cli.sh" "$HOME/.local/bin/amerc-outpost-cli"
nohup "$INSTALL_ROOT/run-outpost.sh" >"$INSTALL_ROOT/logs/outpost.stdout.log" 2>"$INSTALL_ROOT/logs/outpost.stderr.log" </dev/null &
printf '%s\n' "$!" >"$INSTALL_ROOT/outpost.pid"
sleep 2
"$INSTALL_ROOT/outpost-cli.sh" status || true
printf '\nInstalled the tiny controller in %s. Run amerc-outpost to configure it.\n' "$INSTALL_ROOT"
printf 'A compatible system Node is reused; otherwise the verified runtime downloads once in the background.\n'
printf 'Change the default local API password immediately on any shared machine.\n'
