#!/bin/bash
# Aperture immutable customer installer bootstrap. No runtime credentials shipped.
set +x
set -euo pipefail
umask 077
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
unset BASH_ENV ENV
if [[ ${EUID} != 0 ]]; then echo "Run this command using sudo or as root." >&2; exit 1; fi
code=''
code_stdin=0
update=0
while (($#)); do
 case "$1" in
  --enrollment-code) [[ $# -ge 2 && $code_stdin == 0 && $update == 0 && -z "$code" ]] || exit 2; code=$2; shift 2 ;;
  --code-stdin) [[ $code_stdin == 0 && $update == 0 && -z "$code" ]] || exit 2; code_stdin=1; shift ;;
  --update) [[ $code_stdin == 0 && -z "$code" ]] || exit 2; update=1; shift ;;
  --help|-h) echo 'Usage: bash install.sh [--code-stdin | --enrollment-code CODE | --update]'; exit 0 ;;
  *) echo 'Unrecognized installer option.' >&2; exit 2 ;;
 esac
done
if ((code_stdin)); then
 if ! IFS= read -r code || [[ ! "$code" =~ ^[A-Za-z0-9_-]{24,256}$ ]]; then
  echo 'A valid enrollment code is required on standard input.' >&2; exit 2
 fi
 exec 0</dev/null
fi
work=$(mktemp -d -t aperture-install.XXXXXXXX)
trap 'rm -rf "$work"' EXIT
if [[ -n "$code" ]]; then printf '%s' "$code" > "$work/code"; fi
unset code
if ! command -v python3 >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1 || [[ ! -f /etc/ssl/certs/ca-certificates.crt ]]; then
 export DEBIAN_FRONTEND=noninteractive
 apt-get update -qq >/dev/null
 apt-get install -y --no-install-recommends python3 ca-certificates curl >/dev/null
fi
curl -q --fail --silent --show-error --noproxy '*' --proxy '' --proto '=https' --tlsv1.2 --max-redirs 0 --connect-timeout 15 --max-time 90 --max-filesize 1048576 'https://get.aperture.sh/releases/2026.11.10.93/install.py' -o "$work/install.py"
printf '%s  %s\n' 'eb815c3dbc8192c4cdd83eecabb60151171be04fbb9b8ed0783ae53807131374' "$work/install.py" | sha256sum --check --status
# Stdin enrollment keeps this parent alive so its trap also handles a stopped
# executor. Legacy argv enrollment uses exec to drop the code from its argv.
if ((update)); then
 exec python3 "$work/install.py" --bootstrap-dir "$work" --update-linked
elif ((code_stdin)); then
 python3 "$work/install.py" --bootstrap-dir "$work" --code-file "$work/code"
elif [[ -f "$work/code" ]]; then
 exec python3 "$work/install.py" --bootstrap-dir "$work" --code-file "$work/code"
else
 exec python3 "$work/install.py" --bootstrap-dir "$work"
fi
