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

# ===OBM-SCRIPT===
# title: Provision an OpenBAM web container on an Incus host
# description: Creates/updates an Incus container with the OpenBAM Apache 2.4 + PHP 8.4-FPM stack, key-only sshd, sudo, runtime dirs, mail relay, resource limits and ingress proxy devices. Runs ON the target server (execute as a file, never as an SSH-piped heredoc).
# usage: obm-container-provision.sh <name> --hostname <name> [--memory 1GiB] [--cpus 2] [--disk 12GiB] [--autostart-priority N] [--ssh-listen-ip IP] [--ssh-listen-port PORT] [--http-listen-port PORT] [--docroot PATH] [--mail-relay HOST:PORT] [--deploy-key FILE] [--helpers-dir DIR]
# category: deploy
# arg: <name>                 "Incus container name (e.g. obm-staging)"
# arg: --hostname             "Container hostname (usually equals <name>; drives the staging/production detection)"
# arg: --memory               "Memory limit (default 1GiB)"
# arg: --cpus                 "CPU limit (default 2)"
# arg: --disk                 "Root disk size override (default 12GiB)"
# arg: --autostart-priority   "boot.autostart.priority value (postgres 5 > obm-live 4 > obm-staging 3)"
# arg: --ssh-listen-ip        "Host IP for the SSH proxy device (staging only, e.g. 10.99.0.2)"
# arg: --ssh-listen-port      "Host port for the SSH proxy device (staging only, e.g. 2222)"
# arg: --http-listen-port     "Host 127.0.0.1 port for the HTTP proxy device (e.g. 8080); host Apache reverse-proxies to it"
# arg: --docroot              "Absolute project DocumentRoot for a catch-all container vhost (e.g. /var/www/projects/dylanwatts.de)"
# arg: --mail-relay           "Postfix relayhost target for outgoing mail (e.g. 10.237.206.1:25); omit to skip mail setup"
# arg: --deploy-key           "Path (on this host) to a public key to authorize for root SSH"
# arg: --helpers-dir          "Directory holding obm-project-permissions.sh / obm-deploy-fw-container.sh to install (default /tmp)"
# ===OBM-SCRIPT-END===

# ======================================================================
# obm-container-provision.sh — Provision an OpenBAM web container
#
#   Runs ON the target Incus server. Push it as a FILE and execute it:
#     scp obm-container-provision.sh root@host:/tmp/
#     ssh root@host 'bash /tmp/obm-container-provision.sh obm-staging ...'
#
#   NEVER pipe this script over SSH (`ssh host 'bash -s' <<EOF`) — nested
#   `incus exec` calls drain the script's stdin (fix 2026-09-12).
#
#   Idempotent: an existing container is started, its config updated,
#   base packages re-checked, sshd/keys re-asserted, proxy devices
#   replaced. Every step prints a `[provision]` marker.
# ======================================================================

NAME=""
HOSTNAME_ARG=""
MEMORY="1GiB"
CPUS="2"
DISK="12GiB"
AUTOSTART_PRIORITY=""
SSH_LISTEN_IP=""
SSH_LISTEN_PORT=""
HTTP_LISTEN_PORT=""
DOCROOT=""
MAIL_RELAY=""
DEPLOY_KEY=""
HELPERS_DIR="/tmp"
IMAGE="debian13"
PROFILE="obm-base"

usage() {
    echo "Usage: $0 <name> --hostname <name> [options]"
    echo ""
    echo "  Provisions an OpenBAM web container on this Incus host."
    echo ""
    echo "  Options:"
    echo "    --hostname <name>          Container hostname (default: <name>)"
    echo "    --memory <size>            Memory limit (default: 1GiB)"
    echo "    --cpus <n>                 CPU limit (default: 2)"
    echo "    --disk <size>              Root disk override (default: 12GiB)"
    echo "    --autostart-priority <n>   boot.autostart.priority (e.g. 3)"
    echo "    --ssh-listen-ip <ip>       Host IP for the SSH proxy device"
    echo "    --ssh-listen-port <port>   Host port for the SSH proxy device"
    echo "    --http-listen-port <port>  Host 127.0.0.1 port for the HTTP proxy device"
    echo "    --docroot <path>           DocumentRoot for a catch-all container vhost"
    echo "    --mail-relay <host:port>   Postfix relayhost (e.g. 10.237.206.1:25)"
    echo "    --deploy-key <file>        Public key file to authorize for root"
    echo "    --helpers-dir <dir>        Dir with helper scripts to install (default /tmp)"
    exit 1
}

step() { echo "[provision] $*"; }

# --- Parse arguments --------------------------------------------------
while [[ $# -gt 0 ]]; do
    case "$1" in
        --hostname)             HOSTNAME_ARG="${2:?}"; shift 2 ;;
        --memory)               MEMORY="${2:?}"; shift 2 ;;
        --cpus)                 CPUS="${2:?}"; shift 2 ;;
        --disk)                 DISK="${2:?}"; shift 2 ;;
        --autostart-priority)   AUTOSTART_PRIORITY="${2:?}"; shift 2 ;;
        --ssh-listen-ip)        SSH_LISTEN_IP="${2:?}"; shift 2 ;;
        --ssh-listen-port)      SSH_LISTEN_PORT="${2:?}"; shift 2 ;;
        --http-listen-port)     HTTP_LISTEN_PORT="${2:?}"; shift 2 ;;
        --docroot)              DOCROOT="${2:?}"; shift 2 ;;
        --mail-relay)           MAIL_RELAY="${2:?}"; shift 2 ;;
        --deploy-key)           DEPLOY_KEY="${2:?}"; shift 2 ;;
        --helpers-dir)          HELPERS_DIR="${2:?}"; shift 2 ;;
        -h|--help)              usage ;;
        -*)                     echo "ERROR: Unknown option: $1"; usage ;;
        *)                      if [[ -z "$NAME" ]]; then NAME="$1"; shift; else echo "ERROR: Unexpected argument: $1"; usage; fi ;;
    esac
done

[[ -n "$NAME" ]] || usage
[[ -n "$HOSTNAME_ARG" ]] || HOSTNAME_ARG="$NAME"

if [[ ! "$NAME" =~ ^[a-z0-9][a-z0-9-]*$ ]]; then
    echo "ERROR: Invalid container name: $NAME (lowercase letters, digits, hyphens)"
    exit 1
fi

# --- Preconditions ----------------------------------------------------
command -v incus >/dev/null 2>&1 || { echo "ERROR: incus not found — run this on an Incus host."; exit 1; }
incus profile show "$PROFILE" >/dev/null 2>&1 || { echo "ERROR: Incus profile not found: $PROFILE"; exit 1; }
incus image info "$IMAGE" >/dev/null 2>&1 || { echo "ERROR: Image alias not found: $IMAGE"; exit 1; }

TMPD="$(mktemp -d)"
trap 'rm -rf "$TMPD"' EXIT

# --- 1. Create or start the container ---------------------------------
if incus info "$NAME" >/dev/null 2>&1; then
    step "container '$NAME' already exists"
    if [[ "$(incus list "$NAME" --format csv -c s | head -1)" != "RUNNING" ]]; then
        step "starting '$NAME'"
        incus start "$NAME"
    fi
else
    step "launching '$NAME' from image '$IMAGE' (profile $PROFILE)"
    incus launch "$IMAGE" "$NAME" --profile "$PROFILE"
fi

step "applying resource limits (memory=$MEMORY cpu=$CPUS autostart=true)"
incus config set "$NAME" limits.memory "$MEMORY"
incus config set "$NAME" limits.cpu "$CPUS"
incus config set "$NAME" boot.autostart true
if [[ -n "$AUTOSTART_PRIORITY" ]]; then
    incus config set "$NAME" boot.autostart.priority "$AUTOSTART_PRIORITY"
fi
if [[ -n "$DISK" ]]; then
    incus config device override "$NAME" root size="$DISK" 2>/dev/null \
        || incus config device set "$NAME" root size="$DISK" 2>/dev/null \
        || step "WARNING: could not set root size=$DISK (device may not be named 'root')"
fi

step "waiting for the container to be responsive"
for _ in $(seq 1 30); do
    if incus exec "$NAME" -- true >/dev/null 2>&1; then break; fi
    sleep 2
done
incus exec "$NAME" -- true >/dev/null 2>&1 || { echo "ERROR: container '$NAME' is not responsive"; exit 1; }

# --- 2. Hostname ------------------------------------------------------
# Incus sets the hostname to the instance name at launch; `hostname` does not
# need dbus (hostnamectl does, and dbus may not be installed yet).
step "setting hostname to '$HOSTNAME_ARG'"
incus exec "$NAME" -- bash -c "hostname '$HOSTNAME_ARG' 2>/dev/null || true; echo '$HOSTNAME_ARG' > /etc/hostname"
incus exec "$NAME" -- bash -c "grep -qE '^127\.0\.1\.1[[:space:]]+$HOSTNAME_ARG' /etc/hosts || echo '127.0.1.1 $HOSTNAME_ARG' >> /etc/hosts"
step "container hostname is now: $(incus exec "$NAME" -- hostname)"

# --- 3. Base stack ----------------------------------------------------
step "installing base stack (Apache 2.4, PHP 8.4-FPM, tools)"
incus exec "$NAME" -- bash -c 'export DEBIAN_FRONTEND=noninteractive; apt-get update -qq'
incus exec "$NAME" -- bash -c 'echo "postfix postfix/main_mailer_type select Satellite system" | debconf-set-selections; echo "postfix postfix/mailname string '"$HOSTNAME_ARG"'" | debconf-set-selections'
incus exec "$NAME" -- bash -c 'export DEBIAN_FRONTEND=noninteractive; apt-get install -y -qq \
    curl wget tar gzip git unzip nano openssh-client openssh-server openssl rsync sudo ca-certificates dbus \
    apache2 \
    php8.4-fpm php8.4-cli \
    php8.4-bcmath php8.4-curl php8.4-gd php8.4-intl \
    php8.4-ldap php8.4-mbstring php8.4-mysql \
    php8.4-pgsql php8.4-sqlite3 php8.4-xml php8.4-zip \
    php8.4-apcu php8.4-igbinary php8.4-yaml \
    php8.4-imagick php8.4-opcache \
    sqlite3 git-lfs postfix'

step "configuring Apache modules and the PHP-FPM handler"
incus exec "$NAME" -- bash -c 'a2enmod -q rewrite proxy proxy_http proxy_wstunnel ssl headers proxy_fcgi || true'
incus exec "$NAME" -- bash -c 'a2dismod -q php8.4 || true'

cat > "$TMPD/php-fpm.conf" <<'PHPCONF'
<FilesMatch ".php$">
    SetHandler "proxy:unix:/run/php/php8.4-fpm.sock|fcgi://localhost/"
</FilesMatch>
PHPCONF
incus file push "$TMPD/php-fpm.conf" "$NAME/etc/apache2/conf-available/php-fpm.conf"
incus exec "$NAME" -- a2enconf -q php-fpm

cat > "$TMPD/openbam-projects.conf" <<'OBMCONF'
<Directory /var/www/projects>
    Options FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
OBMCONF
incus file push "$TMPD/openbam-projects.conf" "$NAME/etc/apache2/conf-available/zz-openbam-projects.conf"
incus exec "$NAME" -- a2enconf -q zz-openbam-projects

if [[ -n "$DOCROOT" ]]; then
    step "writing catch-all vhost (DocumentRoot $DOCROOT)"
    cat > "$TMPD/openbam-vhost.conf" <<VHOST
<VirtualHost *:80>
    DocumentRoot $DOCROOT

    <Directory $DOCROOT>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/openbam_error.log
    CustomLog \${APACHE_LOG_DIR}/openbam_access.log combined
</VirtualHost>
VHOST
    incus file push "$TMPD/openbam-vhost.conf" "$NAME/etc/apache2/sites-available/openbam.conf"
    incus exec "$NAME" -- bash -c 'a2dissite -q 000-default 2>/dev/null || true; a2ensite -q openbam'
fi

incus exec "$NAME" -- apache2ctl configtest
incus exec "$NAME" -- systemctl enable --now apache2 php8.4-fpm
incus exec "$NAME" -- systemctl restart apache2 php8.4-fpm

# --- 4. SSH server (key-only) ----------------------------------------
step "configuring sshd (key-only root access)"
incus exec "$NAME" -- install -d -m 755 /etc/ssh/sshd_config.d
incus exec "$NAME" -- bash -c 'printf "%s\n" "# OpenBAM container policy (managed by obm-container-provision.sh)" "PermitRootLogin prohibit-password" "PasswordAuthentication no" "PubkeyAuthentication yes" > /etc/ssh/sshd_config.d/99-obm.conf'
incus exec "$NAME" -- systemctl enable --now ssh
incus exec "$NAME" -- systemctl reload ssh 2>/dev/null || incus exec "$NAME" -- systemctl restart ssh

if [[ -n "$DEPLOY_KEY" && -f "$DEPLOY_KEY" ]]; then
    KEYLINE="$(head -1 "$DEPLOY_KEY")"
    step "authorizing deploy key for root: ${KEYLINE:0:40}..."
    incus exec "$NAME" -- install -d -m 700 /root/.ssh
    incus exec "$NAME" -- bash -c "touch /root/.ssh/authorized_keys; grep -qxF '$KEYLINE' /root/.ssh/authorized_keys || echo '$KEYLINE' >> /root/.ssh/authorized_keys; chmod 600 /root/.ssh/authorized_keys"
else
    step "WARNING: no --deploy-key given — SSH login will need a key installed later"
fi

# --- 5. Runtime directories + helper scripts --------------------------
step "creating /var/www runtime directories"
incus exec "$NAME" -- install -d -m 755 /var/www/programs /var/www/projects /var/www/bin/bash /var/log/openbam
if [[ -n "$DOCROOT" ]]; then
    step "creating project log directory /var/log/openbam/$(basename "$DOCROOT")"
    incus exec "$NAME" -- install -d -m 755 -o www-data -g www-data "/var/log/openbam/$(basename "$DOCROOT")"
fi

for helper in obm-project-permissions.sh obm-deploy-fw-container.sh obm-sync-project.sh; do
    if [[ -f "$HELPERS_DIR/$helper" ]]; then
        step "installing helper: $helper"
        incus file push "$HELPERS_DIR/$helper" "$NAME/var/www/bin/bash/$helper"
        incus exec "$NAME" -- chmod 755 "/var/www/bin/bash/$helper"
    else
        step "WARNING: helper not found in $HELPERS_DIR: $helper (install it later)"
    fi
done

# --- 6. Mail relay (satellite Postfix) --------------------------------
if [[ -n "$MAIL_RELAY" ]]; then
    if [[ "$MAIL_RELAY" == *:* ]]; then
        RELAY_SPEC="[${MAIL_RELAY%%:*}]:${MAIL_RELAY##*:}"
    else
        RELAY_SPEC="[$MAIL_RELAY]"
    fi
    step "configuring Postfix satellite relay -> $RELAY_SPEC"
    incus exec "$NAME" -- postconf -e "relayhost = $RELAY_SPEC"
    incus exec "$NAME" -- postconf -e "myhostname = $HOSTNAME_ARG"
    incus exec "$NAME" -- postconf -e "inet_interfaces = loopback-only"
    incus exec "$NAME" -- postconf -e "mynetworks = 127.0.0.0/8"
    incus exec "$NAME" -- bash -c "echo '$HOSTNAME_ARG' > /etc/mailname"
    incus exec "$NAME" -- systemctl enable --now postfix
    incus exec "$NAME" -- systemctl restart postfix
else
    step "mail relay not requested — skipping Postfix configuration"
fi

# --- 7. Ingress proxy devices -----------------------------------------
IP4="$(incus list "$NAME" --format csv -c 4 | head -1 | cut -d' ' -f1)"
if [[ -z "$IP4" ]]; then
    echo "ERROR: could not determine the IPv4 address of '$NAME'"
    exit 1
fi
step "container IPv4: $IP4"

if [[ -n "$SSH_LISTEN_PORT" ]]; then
    [[ -n "$SSH_LISTEN_IP" ]] || SSH_LISTEN_IP="0.0.0.0"
    step "SSH proxy device: tcp:$SSH_LISTEN_IP:$SSH_LISTEN_PORT -> $IP4:22"
    incus config device remove "$NAME" ssh >/dev/null 2>&1 || true
    incus config device add "$NAME" ssh proxy listen="tcp:$SSH_LISTEN_IP:$SSH_LISTEN_PORT" connect="tcp:$IP4:22"
else
    step "no SSH proxy requested — SSH reachable over the bridge only"
fi

if [[ -n "$HTTP_LISTEN_PORT" ]]; then
    step "HTTP proxy device: tcp:127.0.0.1:$HTTP_LISTEN_PORT -> $IP4:80"
    incus config device remove "$NAME" http >/dev/null 2>&1 || true
    incus config device add "$NAME" http proxy listen="tcp:127.0.0.1:$HTTP_LISTEN_PORT" connect="tcp:$IP4:80"
fi

# --- 8. Verification summary ------------------------------------------
echo ""
step "=== verification summary ==="
incus list "$NAME" --format csv
step "hostname:        $(incus exec "$NAME" -- hostname)"
step "apache2:         $(incus exec "$NAME" -- systemctl is-active apache2)"
step "php8.4-fpm:      $(incus exec "$NAME" -- systemctl is-active php8.4-fpm)"
step "ssh:             $(incus exec "$NAME" -- systemctl is-active ssh)"
if [[ -n "$MAIL_RELAY" ]]; then
    step "postfix:         $(incus exec "$NAME" -- systemctl is-active postfix)"
fi
step "sudo present:    $(incus exec "$NAME" -- bash -c 'command -v sudo >/dev/null && echo yes || echo no')"
step "limits:          memory=$(incus config get "$NAME" limits.memory) cpu=$(incus config get "$NAME" limits.cpu) autostart=$(incus config get "$NAME" boot.autostart) prio=$(incus config get "$NAME" boot.autostart.priority 2>/dev/null || echo -)"
step "proxy devices:   $(incus config device list "$NAME" | tr '\n' ' ')"
if [[ -n "$SSH_LISTEN_PORT" ]]; then
    step "listening host ports: $(ss -tln | awk '{print $4}' | grep -E ":${SSH_LISTEN_PORT}$|:${HTTP_LISTEN_PORT}$" | tr '\n' ' ')"
fi
step "DONE — container '$NAME' is provisioned"
