#!/usr/bin/env bash
# Environment-bound template. build-install-bundle.py renders the constants.
set -Eeuo pipefail
[[ $# -eq 0 ]] || { printf 'Clinicast bootstrap does not accept overrides.\n' >&2; exit 2; }
[[ $EUID -eq 0 ]] || { printf 'Run with sudo: curl -fsSL %s | sudo bash\n' 'https://install-dev.clinicast.ca' >&2; exit 1; }

ENVIRONMENT='development'
BASE_URL='https://install-dev.clinicast.ca'
CLOUD_URL='https://dev.clinicast.ca'
EXPECTED_ENVIRONMENT='development'
EXPECTED_BASE_URL='https://install-dev.clinicast.ca'
EXPECTED_CLOUD_URL='https://dev.clinicast.ca'
BUNDLE_VERSION='1.0.0'
PINNED_BUNDLE_KEY_B64='LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0NCk1Db3dCUVlESzJWd0F5RUEyNWRtMExmMTdsaTFqTENPUFFVd2J4YmdTWTQ3c2ZDNXFmNDNYNnpwT3VvPQ0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tDQo='
VERIFIER_SHA256='ff9736d8e5e58a5b507c214706fcc04a7939b8ea0ce4433decad4f43fe545c6e'
ARCH='x86_64'
[[ "$ENVIRONMENT" == "$EXPECTED_ENVIRONMENT" && "$BASE_URL" == "$EXPECTED_BASE_URL" && "$CLOUD_URL" == "$EXPECTED_CLOUD_URL" ]] || {
  printf 'Clinicast bootstrap environment and fixed endpoints do not match.\n' >&2
  exit 1
}
WORK="$(mktemp -d /tmp/clinicast-bootstrap.XXXXXX)"
trap 'rm -rf -- "$WORK"' EXIT

[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { printf 'Ubuntu 24.04 x86_64 is required.\n' >&2; exit 1; }
[[ -r /etc/os-release ]] || { printf 'Cannot identify this operating system.\n' >&2; exit 1; }
# shellcheck disable=SC1091
source /etc/os-release
[[ "${ID:-}" == ubuntu && "${VERSION_ID:-}" == 24.04 ]] || { printf 'Ubuntu 24.04 LTS is required.\n' >&2; exit 1; }
if [[ -e /opt/clinicast || -L /opt/clinicast || -e /etc/clinicast || -e /var/lib/clinicast || -e /usr/local/lib/clinicast ]]; then
  printf 'An existing or incomplete Clinicast installation was found; use the approved recovery procedure before retrying.\n' >&2
  exit 1
fi
free_kib="$(df -Pk / | awk 'NR==2 {print $4}')"
[[ "$free_kib" =~ ^[0-9]+$ ]] && (( free_kib >= 8388608 )) || { printf 'At least 8 GiB free space is required.\n' >&2; exit 1; }
maintenance_user="${SUDO_USER:-}"
if [[ -z "$maintenance_user" ]]; then
  maintenance_user="$(getent group sudo | cut -d: -f4 | tr ',' '\n' | head -n1 || true)"
fi
[[ -n "$maintenance_user" && "$maintenance_user" != clinicast ]] || { printf 'No maintenance sudo user found. Create one first: sudo adduser telliswall-admin && sudo usermod -aG sudo telliswall-admin\n' >&2; exit 1; }
id -nG "$maintenance_user" | tr ' ' '\n' | grep -qx sudo || { printf 'Maintenance user %s is not in the sudo group.\n' "$maintenance_user" >&2; exit 1; }
dm="$(systemctl show display-manager.service --property=Id --value 2>/dev/null || true)"
if [[ -n "$dm" ]] && { systemctl is-active --quiet "$dm" || systemctl is-enabled --quiet "$dm"; }; then
  if [[ "$dm" != gdm.service && "$dm" != gdm3.service ]]; then
    printf 'An unrecognized active display manager (%s) prevents installation.\n' "$dm" >&2
    exit 1
  fi
  if [[ "$ENVIRONMENT" != development ]]; then
    printf 'GDM is not permitted by this Clinicast installation environment.\n' >&2
    exit 1
  fi
  # Development GDM is stopped and disabled by authenticated bundle preflight
  # after verification and before package/configuration installation.
fi
command -v curl >/dev/null && command -v python3 >/dev/null && command -v openssl >/dev/null || { printf 'curl, Python 3 and OpenSSL are required for bootstrap verification.\n' >&2; exit 1; }
cloud_host="$(python3 -c 'import sys,urllib.parse;print(urllib.parse.urlparse(sys.argv[1]).hostname)' "$CLOUD_URL")"
getent ahosts "$cloud_host" >/dev/null 2>&1 || { printf 'DNS resolution to Clinicast failed.\n' >&2; exit 1; }
curl --fail --silent --show-error --proto '=https' --tlsv1.2 --max-time 15 --output /dev/null "$CLOUD_URL/" || { printf 'HTTPS connectivity to the configured Clinicast environment failed.\n' >&2; exit 1; }

printf '%s' "$PINNED_BUNDLE_KEY_B64" | base64 -d > "$WORK/bundle-public-key.pem"
curl --fail --silent --show-error --proto '=https' --tlsv1.2 --max-filesize 1048576 --output "$WORK/install-bundle.py" "$BASE_URL/v1/bootstrap/install-bundle.py"
printf '%s  %s\n' "$VERIFIER_SHA256" "$WORK/install-bundle.py" | sha256sum --check --status || { printf 'Bootstrap verifier integrity check failed.\n' >&2; exit 1; }
for suffix in manifest.json manifest.sig tar.gz; do
  limit=1048576
  [[ "$suffix" == tar.gz ]] && limit=1073741824
  [[ "$suffix" == manifest.sig ]] && limit=1024
  curl --fail --silent --show-error --proto '=https' --tlsv1.2 --max-filesize "$limit" --output "$WORK/$suffix" "$BASE_URL/v1/bundles/$BUNDLE_VERSION/$suffix"
done
python3 "$WORK/install-bundle.py" --archive "$WORK/tar.gz" --manifest "$WORK/manifest.json" --signature "$WORK/manifest.sig" --public-key "$WORK/bundle-public-key.pem" --environment "$ENVIRONMENT" --architecture "$ARCH" --bundle-version "$BUNDLE_VERSION" --destination "$WORK/bundle"
if bash "$WORK/bundle/install.sh" --environment "$ENVIRONMENT" --maintenance-user "$maintenance_user"; then
  status=0
else
  status=$?
fi
rm -rf -- "$WORK"
trap - EXIT
exit "$status"
