#!/usr/bin/env bash
#
# Notakey Authentication Appliance - Proxmox VE container installer
#
# Run on the Proxmox VE host, as root:
#
#   bash -c "$(curl -fsSL https://www.notakey.com/install/proxmox-lxc.sh)"
#
# Read it before you run it:
#
#   curl -fsSL https://www.notakey.com/install/proxmox-lxc.sh | less
#
# What this script does, in order:
#   1. Asks for the container settings (ID, hostname, size, storage, network,
#      optional SSH public keys for root).
#   2. Downloads the current Debian 12 container template if it is missing.
#   3. Creates an unprivileged container with the 'nesting' feature that
#      Docker needs (plus 'keyctl', as on our own appliance container), and
#      starts it.
#   4. Inside the container, runs the standard appliance installer
#      (https://www.notakey.com/install/appliance.sh): Docker Engine, then the
#      Notakey configuration wizard.
#
# It changes nothing else on the host: no host packages, no firewall rules, no
# storage or network configuration. If a step fails after the container was
# created, the container is left in place so you can inspect it.
#
# Every question can be answered in advance with an environment variable:
#   NOTAKEY_CT_ID  NOTAKEY_CT_HOSTNAME  NOTAKEY_CT_CORES  NOTAKEY_CT_MEMORY
#   NOTAKEY_CT_SWAP  NOTAKEY_CT_DISK  NOTAKEY_CT_STORAGE
#   NOTAKEY_CT_TEMPLATE_STORAGE  NOTAKEY_CT_BRIDGE  NOTAKEY_CT_VLAN
#   NOTAKEY_CT_IP (dhcp or address/prefix)  NOTAKEY_CT_GATEWAY
#   NOTAKEY_CT_SSH_KEYS (a public key for root, or a file with public keys;
#   empty for none)
#   NOTAKEY_YES=1 accepts every default without asking.

set -euo pipefail

APPLIANCE_SCRIPT_URL="${NOTAKEY_APPLIANCE_SCRIPT_URL:-https://www.notakey.com/install/appliance.sh}"

say()  { printf '==> %s\n' "$*"; }
note() { printf '    %s\n' "$*"; }
warn() { printf 'WARNING: %s\n' "$*" >&2; }
die()  { printf 'ERROR: %s\n' "$*" >&2; exit 1; }

ask() {
  # ask VARIABLE "question" "default"; an already-set variable is not asked.
  local var="$1" question="$2" default="$3" current answer
  current="${!var:-}"
  if [ -n "$current" ]; then
    return 0
  fi
  if [ "${NOTAKEY_YES:-0}" = "1" ]; then
    printf -v "$var" '%s' "$default"
    return 0
  fi
  read -r -p "$question [$default]: " answer
  printf -v "$var" '%s' "${answer:-$default}"
}

confirm() {
  local answer
  if [ "${NOTAKEY_YES:-0}" = "1" ]; then
    return 0
  fi
  read -r -p "$1 [y/N] " answer
  case "$answer" in
    y | Y | yes | YES) return 0 ;;
    *) return 1 ;;
  esac
}

first_storage_with() {
  # first_storage_with CONTENT [preferred names...] -> name of an active storage
  local content="$1" available preferred
  shift
  available="$(pvesm status -content "$content" 2>/dev/null | awk 'NR > 1 && $3 == "active" {print $1}')"
  for preferred in "$@"; do
    if printf '%s\n' "$available" | grep -qx "$preferred"; then
      printf '%s\n' "$preferred"
      return 0
    fi
  done
  printf '%s\n' "$available" | head -n 1
}

# --- Preconditions -----------------------------------------------------------

[ "$(id -u)" -eq 0 ] || die "run this as root on the Proxmox VE host."
for tool in pct pveam pvesm pvesh; do
  command -v "$tool" >/dev/null 2>&1 || die "'$tool' not found. This script must run on a Proxmox VE host."
done
if [ ! -t 0 ] || [ ! -t 1 ]; then
  die "the configuration wizard needs a terminal. Do not pipe this script into
  bash; run it like this instead:
  bash -c \"\$(curl -fsSL https://www.notakey.com/install/proxmox-lxc.sh)\""
fi
arch="$(uname -m)"
[ "$arch" = "x86_64" ] || die "unsupported CPU architecture '$arch': the appliance images are built for x86-64 only."

say "Notakey Authentication Appliance on Proxmox VE"
note "Host: $(hostname) - $(pveversion 2>/dev/null | head -n 1)"
echo

# --- 1. Settings -------------------------------------------------------------

CT_ID="${NOTAKEY_CT_ID:-}"
CT_HOSTNAME="${NOTAKEY_CT_HOSTNAME:-}"
CT_CORES="${NOTAKEY_CT_CORES:-}"
CT_MEMORY="${NOTAKEY_CT_MEMORY:-}"
CT_SWAP="${NOTAKEY_CT_SWAP:-}"
CT_DISK="${NOTAKEY_CT_DISK:-}"
CT_STORAGE="${NOTAKEY_CT_STORAGE:-}"
CT_TEMPLATE_STORAGE="${NOTAKEY_CT_TEMPLATE_STORAGE:-}"
CT_BRIDGE="${NOTAKEY_CT_BRIDGE:-}"
CT_VLAN="${NOTAKEY_CT_VLAN-unset}"
CT_IP="${NOTAKEY_CT_IP:-}"
CT_GATEWAY="${NOTAKEY_CT_GATEWAY:-}"
CT_SSH_KEYS="${NOTAKEY_CT_SSH_KEYS-unset}"

default_storage="$(first_storage_with rootdir local-lvm local-zfs)"
default_template_storage="$(first_storage_with vztmpl local)"
[ -n "$default_storage" ] || die "no active storage accepts container disks (content type 'rootdir')."
[ -n "$default_template_storage" ] || die "no active storage accepts container templates (content type 'vztmpl')."

ask CT_ID "Container ID" "$(pvesh get /cluster/nextid)"
ask CT_HOSTNAME "Hostname" "notakey"
ask CT_CORES "CPU cores" "2"
ask CT_MEMORY "Memory in MB" "2048"
ask CT_SWAP "Swap in MB" "512"
ask CT_DISK "Disk size in GB" "20"
ask CT_STORAGE "Storage for the container disk" "$default_storage"
ask CT_TEMPLATE_STORAGE "Storage for the template" "$default_template_storage"
ask CT_BRIDGE "Network bridge" "vmbr0"
if [ "$CT_VLAN" = "unset" ]; then
  CT_VLAN=""
  if [ "${NOTAKEY_YES:-0}" != "1" ]; then
    read -r -p "VLAN tag (empty for none) []: " CT_VLAN
  fi
fi
ask CT_IP "IPv4 address with prefix, or dhcp" "dhcp"
if [ "$CT_IP" != "dhcp" ]; then
  ask CT_GATEWAY "Gateway" ""
fi
if [ "$CT_SSH_KEYS" = "unset" ]; then
  CT_SSH_KEYS=""
  if [ "${NOTAKEY_YES:-0}" != "1" ]; then
    note "The container gets no root password. Without SSH keys you reach it with 'pct enter' from this host."
    read -r -p "Paste an SSH public key for root (empty for none) []: " CT_SSH_KEYS
  fi
fi

case "$CT_ID" in '' | *[!0-9]*) die "container ID must be a number." ;; esac
# CT_SSH_KEYS is either a pasted public key or the path of a file with keys.
ssh_key_file=""
ssh_key_label=""
if [ -n "$CT_SSH_KEYS" ]; then
  case "$CT_SSH_KEYS" in
    *"PRIVATE KEY"*) die "that is a private key; paste the public key (the .pub file)." ;;
    ssh-* | ecdsa-* | sk-*)
      ssh_key_file="$(mktemp)"
      trap 'rm -f "$ssh_key_file"' EXIT
      printf '%s\n' "$CT_SSH_KEYS" >"$ssh_key_file"
      ssh_key_label="the pasted key ($(printf '%s' "$CT_SSH_KEYS" | awk '{print $1, $3}'))"
      ;;
    *)
      [ -r "$CT_SSH_KEYS" ] || die "that is neither an SSH public key (ssh-ed25519 ..., ssh-rsa ...) nor a readable file."
      grep -qE '^(ssh-|ecdsa-|sk-)' "$CT_SSH_KEYS" || die "$CT_SSH_KEYS contains no SSH public key."
      ssh_key_file="$CT_SSH_KEYS"
      ssh_key_label="the keys in $CT_SSH_KEYS"
      ;;
  esac
  if command -v ssh-keygen >/dev/null 2>&1; then
    ssh-keygen -l -f "$ssh_key_file" >/dev/null 2>&1 || die "the SSH public key is not valid (was it pasted completely, on one line?)."
  fi
fi
for number in "$CT_CORES" "$CT_MEMORY" "$CT_SWAP" "$CT_DISK"; do
  case "$number" in '' | *[!0-9]*) die "cores, memory, swap and disk must be whole numbers." ;; esac
done
case "$CT_VLAN" in *[!0-9]*) die "VLAN tag must be a number or empty." ;; esac
case "$CT_HOSTNAME" in '' | *[!A-Za-z0-9-]*) die "hostname may contain only letters, digits and '-'." ;; esac
ipv4='([0-9]{1,3}\.){3}[0-9]{1,3}'
if [ "$CT_IP" != "dhcp" ]; then
  [[ "$CT_IP" =~ ^${ipv4}/([0-9]|[12][0-9]|3[0-2])$ ]] ||
    die "the IPv4 address must be 'dhcp' or an address with a prefix, for example 192.168.1.50/24."
  if [ -n "$CT_GATEWAY" ]; then
    [[ "$CT_GATEWAY" =~ ^${ipv4}$ ]] || die "the gateway must be an IPv4 address, for example 192.168.1.1."
  else
    warn "no gateway given: the container will not reach the internet and the installation will stop."
  fi
fi
[ -d "/sys/class/net/$CT_BRIDGE/bridge" ] || die "there is no network bridge '$CT_BRIDGE' on this host."
pvesm status --content rootdir 2>/dev/null | awk 'NR > 1 && $3 == "active" {print $1}' | grep -qx "$CT_STORAGE" ||
  die "storage '$CT_STORAGE' is not active or does not accept container disks."
pvesm status --content vztmpl 2>/dev/null | awk 'NR > 1 && $3 == "active" {print $1}' | grep -qx "$CT_TEMPLATE_STORAGE" ||
  die "storage '$CT_TEMPLATE_STORAGE' is not active or does not accept container templates."
# /cluster/nextid with an explicit ID fails if any guest on any node has it.
if ! pvesh get /cluster/nextid --vmid "$CT_ID" >/dev/null 2>&1; then
  die "ID $CT_ID is not available (in use on this host or elsewhere in the cluster, or out of range)."
fi

net0="name=eth0,bridge=${CT_BRIDGE}"
[ -n "$CT_VLAN" ] && net0="${net0},tag=${CT_VLAN}"
if [ "$CT_IP" = "dhcp" ]; then
  net0="${net0},ip=dhcp"
else
  net0="${net0},ip=${CT_IP}"
  [ -n "$CT_GATEWAY" ] && net0="${net0},gw=${CT_GATEWAY}"
fi

echo
say "About to create"
note "Container:  $CT_ID ($CT_HOSTNAME), unprivileged, features nesting=1,keyctl=1"
note "Size:       $CT_CORES cores, $CT_MEMORY MB memory, $CT_SWAP MB swap, $CT_DISK GB on $CT_STORAGE"
note "Network:    $net0"
note "Template:   Debian 12 (standard), kept on $CT_TEMPLATE_STORAGE"
if [ -n "$CT_SSH_KEYS" ]; then
  note "Access:     pct enter $CT_ID, or SSH as root with $ssh_key_label"
else
  note "Access:     pct enter $CT_ID from this host (no SSH keys, no root password)"
fi
echo
confirm "Create the container and install the appliance?" || die "aborted, nothing was changed."

# --- 2. Template -------------------------------------------------------------

say "Looking for the Debian 12 template"
pveam update >/dev/null
template="$(pveam available --section system | awk '$2 ~ /^debian-12-standard_.*_amd64/ {print $2}' | sort -V | tail -n 1)"
[ -n "$template" ] || die "no Debian 12 template in the Proxmox template index."
if pveam list "$CT_TEMPLATE_STORAGE" 2>/dev/null | grep -q "$template"; then
  note "$template is already on $CT_TEMPLATE_STORAGE"
else
  note "Downloading $template to $CT_TEMPLATE_STORAGE"
  pveam download "$CT_TEMPLATE_STORAGE" "$template" >/dev/null
fi

# --- 3. Container ------------------------------------------------------------

say "Creating container $CT_ID"
ssh_args=()
[ -n "$ssh_key_file" ] && ssh_args=(--ssh-public-keys "$ssh_key_file")
pct create "$CT_ID" "${CT_TEMPLATE_STORAGE}:vztmpl/${template}" \
  --hostname "$CT_HOSTNAME" \
  --ostype debian \
  --cores "$CT_CORES" \
  --memory "$CT_MEMORY" \
  --swap "$CT_SWAP" \
  --rootfs "${CT_STORAGE}:${CT_DISK}" \
  --net0 "$net0" \
  --unprivileged 1 \
  --features nesting=1,keyctl=1 \
  --onboot 1 \
  --tags notakey \
  "${ssh_args[@]}" \
  --description "Notakey Authentication Appliance. Manage it with: pct enter $CT_ID, then 'ntk'." \
  >/dev/null

left_behind() {
  warn "the installation did not finish. Container $CT_ID was left in place."
  note "Inspect it:  pct enter $CT_ID"
  note "Remove it:   pct stop $CT_ID; pct destroy $CT_ID"
}
trap left_behind ERR

pct start "$CT_ID"

say "Waiting for the container's network"
online=0
for _ in $(seq 1 30); do
  if pct exec "$CT_ID" -- getent hosts download.docker.com >/dev/null 2>&1; then
    online=1
    break
  fi
  sleep 2
done
if [ "$online" -ne 1 ]; then
  trap - ERR
  ct_ip="$(pct exec "$CT_ID" -- hostname -I 2>/dev/null | tr ' ' '\n' | grep -m1 -E '^[0-9]+\.' || true)"
  if [ -z "$ct_ip" ]; then
    warn "the container got no IPv4 address on $net0."
    note "With DHCP this usually means a wrong VLAN tag or bridge, or no DHCP server on that network."
  else
    warn "the container has the address $ct_ip but cannot resolve download.docker.com."
    note "Check the gateway and the DNS servers the container was given."
  fi
  note "Fix the network and finish the installation without starting over:"
  note "  pct set $CT_ID -net0 name=eth0,bridge=<bridge>,tag=<vlan>,ip=dhcp"
  note "  pct reboot $CT_ID"
  note "  pct exec $CT_ID -- bash -c 'apt-get update && apt-get install -y curl ca-certificates'"
  note "  pct enter $CT_ID    # then run: bash -c \"\$(curl -fsSL $APPLIANCE_SCRIPT_URL)\""
  note "Or remove the container and run this script again:"
  note "  pct stop $CT_ID; pct destroy $CT_ID"
  exit 1
fi
note "Address: $(pct exec "$CT_ID" -- hostname -I 2>/dev/null | awk '{print $1}')"

# --- 4. Appliance ------------------------------------------------------------

say "Preparing the container"
# LC_ALL=C: the host's locale is usually not generated in a fresh container.
pct exec "$CT_ID" -- env LC_ALL=C LANG=C DEBIAN_FRONTEND=noninteractive bash -c 'apt-get update -qq && apt-get install -y -qq curl ca-certificates >/dev/null 2>&1'

say "Running the appliance installer inside the container"
pct exec "$CT_ID" -- env LC_ALL=C LANG=C NOTAKEY_YES=1 bash -c "bash -c \"\$(curl -fsSL '$APPLIANCE_SCRIPT_URL')\""

trap - ERR
echo
ct_addr="$(pct exec "$CT_ID" -- hostname -I 2>/dev/null | awk '{print $1}')"
if ! pct exec "$CT_ID" -- test -f /opt/notakey/cfg/.env; then
  say "The container is ready, but the appliance is not installed in it yet"
  note "Container $CT_ID ($CT_HOSTNAME), address $ct_addr"
  note "To install it, open a shell with 'pct enter $CT_ID' and run:"
  note "  bash -c \"\$(curl -fsSL $APPLIANCE_SCRIPT_URL)\""
  exit 0
fi
say "Done"
ct_addr="$(pct exec "$CT_ID" -- hostname -I 2>/dev/null | awk '{print $1}')"
note "Container $CT_ID ($CT_HOSTNAME), address $ct_addr"
note "Open a shell in it:  pct enter $CT_ID"
[ -n "$CT_SSH_KEYS" ] && note "Or over SSH:         ssh root@$ct_addr"
note "Manage the appliance there with the 'ntk' command."
