#!/usr/bin/env bash
set -euo pipefail
umask 077

if [[ ${1:-} == --help ]]; then
  printf 'Usage: bash install-nookins.sh --home /absolute/path/to/NEW-home\n'
  exit 0
fi
if [[ $# != 2 || $1 != --home || $2 != /* ]]; then
  printf 'Usage: bash install-nookins.sh --home /absolute/path/to/NEW-home\n' >&2
  exit 2
fi
nookins_bootstrap_home=$2
case "$nookins_bootstrap_home" in
  /|*/|*/../*|*/./*|*/..|*/.|*//*) printf 'Choose a normalized absolute home path.\n' >&2; exit 2 ;;
esac
if [[ $(uname -s) != Linux || $(uname -m) != x86_64 ]]; then
  printf 'This alpha installer supports Linux x86_64.\n' >&2
  exit 2
fi
for tool in curl sha256sum tar; do command -v "$tool" >/dev/null; done
if [[ -e $nookins_bootstrap_home || -L $nookins_bootstrap_home ]]; then
  printf 'Choose a new home; preserving existing path: %s\n' "$nookins_bootstrap_home" >&2
  exit 1
fi
nookins_download="${nookins_bootstrap_home}.bootstrap-download"
mkdir -- "$nookins_download"
nookins_archive="nookins-0.42.1-alpha.1-linux-x86_64.tar.gz"
printf 'Downloading Nookins 0.42.1-alpha.1. Recovery files remain in %s\n' "$nookins_download"
curl --fail --silent --show-error --proto '=https' --tlsv1.2 \
  --connect-timeout 15 --max-time 300 --max-filesize 536870912 \
  "https://nookins.app/downloads/$nookins_archive" \
  --output "$nookins_download/$nookins_archive"
(
  cd -- "$nookins_download"
  printf '%s  %s\n' 'd6cc716d156094f4660ee839292fcc1c51910bc5cf44612d5540224e752cf886' "$nookins_archive" | sha256sum --check --status
)
# This script, executable and root use HTTPS initial trust. Native verification
# authenticates fresh signed metadata before consuming this same archive.
if [[ 'application-v1' == legacy-bootstrap-v1 ]]; then
  tar --extract --gzip --file "$nookins_download/$nookins_archive" \
    --directory "$nookins_download" --no-same-owner
  exec bash "$nookins_download/nookins-install/install.sh" --home "$nookins_bootstrap_home"
fi
if [[ 'application-v1' != application-v1 ]]; then
  printf 'Unsupported application archive profile.\n' >&2; exit 1
fi
# Extract only fixed regular application paths; the site preparation verifier
# rejects links, duplicate names and all unlisted archive members before release.
tar --extract --gzip --file "$nookins_download/$nookins_archive" \
  --directory "$nookins_download" --no-same-owner -- \
  generation-v1/bin/nookins generation-v1/release-manifest.json \
  generation-v1/manifest.json generation-v1/assets/agent-workspace-v1/manifest.json \
  generation-v1/assets/agent-workspace-v1/component.json \
  generation-v1/LICENSE-APACHE generation-v1/LICENSE-MIT generation-v1/NOTICE.md
nookins_binary="$nookins_download/generation-v1/bin/nookins"
if ! "$nookins_binary" --version >/dev/null; then
  printf 'This build requires Linux x86_64 with glibc 2.39 or newer.\n' >&2; exit 1
fi
nookins_source="${nookins_bootstrap_home}.update-source"
nookins_trust="${nookins_bootstrap_home}.update-trust"
nookins_operation="${nookins_bootstrap_home}.install-operation"
for existing in "$nookins_bootstrap_home" "$nookins_source" "$nookins_trust" "$nookins_operation" "${nookins_bootstrap_home}.update.json" "${nookins_bootstrap_home}.update-state" "${nookins_bootstrap_home}.update-operations"; do
  if [[ -e $existing || -L $existing ]]; then
    printf 'Preserving existing installation/recovery path: %s\n' "$existing" >&2; exit 1
  fi
done
curl --fail --silent --show-error --proto '=https' --tlsv1.2 \
  --connect-timeout 15 --max-time 60 --max-filesize 8388608 \
  https://nookins.app/updates/root.json --output "$nookins_download/root.json"
printf '%s  %s\n' '495be108a7d0c0faa602cd68c553bb6b7ba91e9ded16d1974dbfe48ab2e3526e' "$nookins_download/root.json" | sha256sum --check --status
mkdir -- "$nookins_source"
install -m 0600 -- "$nookins_download/root.json" "$nookins_source/root.json"
printf '%s\n' '{"schema":1,"transport":"https","metadata":"https://nookins.app/updates/metadata/","targets":"https://nookins.app/updates/targets/"}' > "$nookins_source/repository.json"
"$nookins_binary" --home "$nookins_bootstrap_home" update --configure \
  --repository "$nookins_source/repository.json" --trusted-root "$nookins_source/root.json"
nookins_install_args=(--home "$nookins_bootstrap_home" maintenance release)
nookins_auth_args=(--trust-store "$nookins_trust" --metadata https://nookins.app/updates/metadata/ \
  --targets https://nookins.app/updates/targets/ --version 0.42.1-alpha.1 \
  --channel alpha --operation "$nookins_operation" --archive "$nookins_download/$nookins_archive")
if ! "$nookins_binary" "${nookins_install_args[@]}" install-authenticated-https "${nookins_auth_args[@]}"; then
  printf '\nInstallation did not complete; preserve all created paths.\n' >&2
  nookins_retry=install-authenticated-https
  if [[ -f $nookins_operation/operation.json && ! -L $nookins_operation/operation.json ]]; then
    nookins_retry=recover-authenticated-https
  elif [[ -e $nookins_operation || -L $nookins_operation ]]; then
    printf 'Incomplete operation record: preserve it for inspection before retrying.\n' >&2; exit 1
  fi
  printf 'After resolving the error, retry the recorded inputs:\n  ' >&2
  printf '%q ' "$nookins_binary" "${nookins_install_args[@]}" "$nookins_retry" "${nookins_auth_args[@]}" >&2
  printf '\n' >&2
  exit 1
fi
# Older application archives remain selectable and do not implement consolidation.
nookins_version='0.42.1-alpha.1'
if [[ $nookins_version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]] &&
  (( 10#${BASH_REMATCH[1]} > 0 || 10#${BASH_REMATCH[2]} > 41 ||
     (10#${BASH_REMATCH[2]} == 41 && 10#${BASH_REMATCH[3]} >= 1) )); then
  if ! "$nookins_bootstrap_home/bin/nookins" --home "$nookins_bootstrap_home" maintenance consolidate; then
    printf '\nNookins was installed, but maintenance consolidation did not complete. Preserve all remaining paths.\n' >&2
    printf 'After resolving the error, resume consolidation with the installed binary:\n  ' >&2
    printf '%q ' "$nookins_bootstrap_home/bin/nookins" --home "$nookins_bootstrap_home" maintenance consolidate >&2
    printf '\n' >&2
    exit 1
  fi
fi
printf '\nInstalled and left stopped. Continue with provider/account setup:\n  %q --home %q onboard\n\nAdd to PATH in this shell:\n  export NOOKINS_HOME=%q\n  export PATH=%q:"$PATH"\n' \
  "$nookins_bootstrap_home/bin/nookins" "$nookins_bootstrap_home" "$nookins_bootstrap_home" "$nookins_bootstrap_home/bin"
