#!/bin/sh
# ADR-0040 M10: native appliance first-boot orchestration -- credential
# rotation and a startup summary, run once via argus-firstboot.service
# (ConditionPathExists=!/var/lib/argus/.provisioned gates re-runs at the
# systemd level; this script also checks and writes that marker itself, so
# a manual re-run stays a safe no-op even outside that gating).
#
# What M10's spec asks for that DOESN'T need doing here, because it's
# already automatic elsewhere in this codebase:
#   - Self-signed TLS cert generation: uiserver.go's ensureSelfSignedCert
#     runs on every argus-api start whenever ARGUS_UI_DIST_PATH is set
#     (which argus.env always sets on the native appliance).
#   - DNS 127.0.0.53 stub-resolver conflict detection: resolver.go's
#     checkResolvedStubConflict, already shipped, already automatic.
#   - Database role/database provisioning: argus-db-provision, already
#     invoked from argus-api's own postinst. Peer-authenticated, no
#     password to generate at all -- a real structural simplification over
#     argus-installer/install.sh's own DB_PASSWORD generation step, which
#     only exists because the Docker deployment's Postgres is networked.
#
# What's actually left, mirroring install.sh's steps 7-9 for a machine that
# has no interactive terminal watching it: wait for health, rotate the
# default admin/admin credentials, and print the result somewhere an
# operator with only a serial console will actually see it (this script's
# stdout/stderr go to both journal and console via the unit's
# StandardOutput=journal+console -- do not add a second, manual write to
# /dev/console here, argus-firstboot.service runs as the unprivileged
# `argus` user, which does not reliably have write access to the console
# device node itself; systemd's own forwarding handles that regardless of
# which user the unit runs as).
set -eu

MARKER=/var/lib/argus/.provisioned
API_BASE="http://127.0.0.1:8080/api/v1"
HEALTH_URL="http://127.0.0.1:8080/health"

if [ -f "$MARKER" ]; then
    echo "[argus-firstboot] Already provisioned ($MARKER exists) -- nothing to do."
    exit 0
fi

echo "[argus-firstboot] ARGUS first-boot starting..."
echo "[argus-firstboot] Waiting for argus-api to become healthy..."

READY=false
i=0
while [ "$i" -lt 60 ]; do
    if curl -fsS "$HEALTH_URL" >/dev/null 2>&1; then
        READY=true
        break
    fi
    i=$((i + 1))
    sleep 5
done

if [ "$READY" != "true" ]; then
    echo "[argus-firstboot] ERROR: argus-api did not become healthy within 5 minutes." >&2
    echo "[argus-firstboot] Check: systemctl status argus-api ; journalctl -u argus-api -n 100" >&2
    exit 1
fi
echo "[argus-firstboot] argus-api is healthy."

# ── Rotate the default admin credentials (same API sequence
# argus-installer/install.sh's own step 8 uses against the Docker
# deployment -- kept identical on purpose, ADR-0015's branding/
# installation-consistency requirement applied across deployment models) ──
ADMIN_USER="admin"
ADMIN_PASSWORD="Ax9!$(openssl rand -base64 24 | tr -dc 'A-Za-z0-9' | head -c 20)"

LOGIN_RESP="$(curl -fsS -X POST "${API_BASE}/auth/login" \
    -H 'Content-Type: application/json' \
    -d '{"username":"admin","password":"admin"}' 2>/dev/null || true)"
TOKEN="$(printf '%s' "${LOGIN_RESP}" | grep -oP '"token"\s*:\s*"\K[^"]+' || true)"

CREDS_ROTATED=false
if [ -n "$TOKEN" ]; then
    CHANGE_CODE="$(curl -fsS -o /dev/null -w '%{http_code}' -X POST "${API_BASE}/auth/change-credentials" \
        -H 'Content-Type: application/json' \
        -H "Authorization: Bearer ${TOKEN}" \
        -d "{\"current_password\":\"admin\",\"new_username\":\"${ADMIN_USER}\",\"new_password\":\"${ADMIN_PASSWORD}\",\"new_password_confirm\":\"${ADMIN_PASSWORD}\"}" 2>/dev/null || echo "000")"
    if [ "$CHANGE_CODE" = "200" ]; then
        CREDS_ROTATED=true
    fi
fi

IP_ADDR="$(hostname -I 2>/dev/null | awk '{print $1}')"
IP_ADDR="${IP_ADDR:-localhost}"

echo ""
echo "=============================================================="
echo " ARGUS Security Platform -- first-boot complete"
echo "=============================================================="
echo ""
echo " Access URL:   https://${IP_ADDR}:81  (accept the self-signed certificate)"
if [ "$CREDS_ROTATED" = "true" ]; then
    echo " Username:     ${ADMIN_USER}"
    echo " Password:     ${ADMIN_PASSWORD}"
    echo ""
    echo " Save this password now -- it is not stored anywhere and cannot be recovered."
else
    echo " Could not auto-rotate the default admin credentials (already changed on a"
    echo " prior attempt?). Log in with your existing credentials, or admin/admin on a"
    echo " genuinely fresh install."
fi
echo ""
echo " Next steps:"
echo "  1. Open the administration panel at the Access URL above."
echo "  2. Complete the first-run setup wizard (regional settings, guided protection"
echo "     checklist)."
echo "  3. Configure domains and reverse proxy hosts under Proxy Hosts."
echo "  4. Review the ANIS threat intelligence connection under Threat Intel."
echo "  5. Review security policies in the Security Policy Center."
echo ""
echo " Configuration: /etc/argus/argus.env and /etc/argus/conf.d/*.env"
echo " Upgrade:       apt upgrade"
echo " Logs:          journalctl -u argus-api -u argus-nginx"
echo "=============================================================="
echo ""

touch "$MARKER"
echo "[argus-firstboot] First-boot complete. Marker written: $MARKER"
