#!/bin/bash
# ipa-first-boot.sh — runs once on first container start via ipa-first-boot.service
#
# Required environment variables:
#   IPA_DOMAIN            IPA domain  (e.g. corp.example.com)
#   IPA_ADMIN_PASSWORD    Admin UI / API password
#   IPA_DM_PASSWORD       Directory Manager (LDAP root) password
#
# Optional environment variables:
#   IPA_REALM             Kerberos realm        (default: DOMAIN uppercased)
#   IPA_HOSTNAME          Server FQDN           (default: container hostname)
#   IPA_SETUP_DNS         Enable integrated DNS (default: false)
#   IPA_DNS_FORWARDER     DNS forwarder IP
#   IPA_AUTO_REVERSE      Auto reverse DNS zone (default: false)
#   IPA_SETUP_KRA         Install KRA           (default: false)
#   IPA_NO_NTP            Disable NTP setup     (default: true)
#   IPA_INSTALL_OPTS      Extra verbatim flags for ipa-server-install

set -euo pipefail

LOG=/var/log/ipa-first-boot.log
exec > >(tee -a "$LOG") 2>&1
echo "=== ipa-first-boot: $(date) ==="

if [[ -f /etc/ipa/default.conf ]]; then
    echo "FreeIPA already configured — skipping."
    exit 0
fi

: "${IPA_DOMAIN:?IPA_DOMAIN is required}"
: "${IPA_ADMIN_PASSWORD:?IPA_ADMIN_PASSWORD is required}"
: "${IPA_DM_PASSWORD:?IPA_DM_PASSWORD is required}"

IPA_REALM="${IPA_REALM:-${IPA_DOMAIN^^}}"
IPA_HOSTNAME="${IPA_HOSTNAME:-$(hostname -f)}"
IPA_SETUP_DNS="${IPA_SETUP_DNS:-false}"
IPA_AUTO_REVERSE="${IPA_AUTO_REVERSE:-false}"
IPA_SETUP_KRA="${IPA_SETUP_KRA:-false}"
IPA_NO_NTP="${IPA_NO_NTP:-true}"

ARGS=(
    --realm="$IPA_REALM"
    --domain="$IPA_DOMAIN"
    --admin-password="$IPA_ADMIN_PASSWORD"
    --ds-password="$IPA_DM_PASSWORD"
    --hostname="$IPA_HOSTNAME"
    --ip-address="$(hostname -I | awk '{print $1}')"
    --mkhomedir
    --unattended
    --skip-mem-check
)

if [[ "$IPA_SETUP_DNS" == "true" ]]; then
    ARGS+=(--setup-dns)
    [[ -n "${IPA_DNS_FORWARDER:-}" ]] \
        && ARGS+=(--forwarder="$IPA_DNS_FORWARDER") \
        || ARGS+=(--no-forwarders)
    [[ "$IPA_AUTO_REVERSE" == "true" ]] && ARGS+=(--auto-reverse) || ARGS+=(--no-reverse)
fi

[[ "$IPA_NO_NTP"    == "true"  ]] && ARGS+=(--no-ntp)
[[ "$IPA_SETUP_KRA" == "true"  ]] && ARGS+=(--setup-kra)
[[ -n "${IPA_INSTALL_OPTS:-}"  ]] && read -ra EXTRA <<< "$IPA_INSTALL_OPTS" && ARGS+=("${EXTRA[@]}")

echo "Running ipa-server-install..."
ipa-server-install "${ARGS[@]}"

# Persist key directories to /data volume so they survive container restarts
if mountpoint -q /data 2>/dev/null; then
    echo "Persisting data to /data..."
    for d in /var/lib/dirsrv /var/lib/ipa /etc/ipa /etc/dirsrv \
              /etc/named.conf /var/lib/named /var/lib/krb5kdc; do
        [[ -e "$d" ]] && rsync -a --relative "$d" /data/ 2>/dev/null || true
    done
fi

echo "=== ipa-first-boot complete: $(date) ==="
