#!/usr/bin/env bash
# NUSAPOD installer.
set -euo pipefail
if [ -z "${LICENSE:-}" ]; then
  echo "ERROR: set LICENSE=<your-license-token>." >&2
  echo "  curl -sfL https://get.nusapod.app | sudo LICENSE=<your-license-token> bash" >&2
  exit 1
fi
# a license token is base64url + dots only; reject anything else (blocks header/arg injection)
case "${LICENSE}" in *[!A-Za-z0-9._-]*) echo "ERROR: malformed license token." >&2; exit 1 ;; esac
_base="${NUSAPOD_GET:-https://get.nusapod.app}"
_cfg="$(mktemp)"; _tmp="$(mktemp)"; trap 'rm -f "$_cfg" "$_tmp"' EXIT
# pass the token via a 0600 curl config, NOT the arg list (keeps it out of ps/procfs)
printf 'header = "Authorization: Bearer %s"\n' "${LICENSE}" > "$_cfg"
_code="$(curl -sf --proto '=https' --tlsv1.2 -m 30 -w '%{http_code}' \
  -K "$_cfg" -o "$_tmp" "${_base}/server" 2>/dev/null || true)"
case "${_code}" in
  200) : ;;
  401|403) echo "ERROR: invalid, revoked, expired, or suspended license. Contact hello@nusapod.app." >&2; exit 1 ;;
  429) echo "ERROR: too many requests — wait a minute and retry." >&2; exit 1 ;;
  *) echo "ERROR: could not reach the installer service (status ${_code:-000}). Check connectivity and retry." >&2; exit 1 ;;
esac
bash "$_tmp"
