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

###############################################################################
# install-systemd-worker-units.sh
#
# Idempotently installs the WHP sandboxed worker template units:
#   - whp-cpanel-import@.service  (shipped 2026.05.183)
#   - whp-bulk-sites@.service     (shipped 2026.05.197)
#
# Why this exists separately from the per-feature staging scripts that
# already ship those units: update.sh runs per-version scripts from the
# extracted tarball BEFORE rsyncing configs/ into /root/whp/. The original
# setup-cpanel-import-isolation.sh and setup-bulk-sites-worker.sh both
# looked for the unit file at /root/whp/configs/<name>, which is the
# PREVIOUS release's configs/ tree at that point in the update flow — so
# the unit was silently skipped on every existing-server upgrade. (Fresh
# installs were unaffected because setup.sh handles them inline.)
#
# This script resolves the unit files via $BASH_SOURCE-relative paths,
# which point INTO the tarball extract dir while apply-scripts.sh is
# running and therefore see the units shipped by THIS release.
#
# Fully idempotent: re-running is a no-op when both units are already
# installed and current.
#
# See CLAUDE.md "Not assume /root/whp/configs/ is current at script-run
# time" + feedback memory notes.
###############################################################################

echo "=== Installing systemd worker units (cpanel-import + bulk-sites) ==="

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

resolve_unit_src() {
    local unit_name="$1"
    local candidate
    for candidate in \
        "$SCRIPT_DIR/../../../configs/$unit_name" \
        "/root/whp/configs/$unit_name" ; do
        if [ -f "$candidate" ]; then
            echo "$candidate"
            return 0
        fi
    done
    return 1
}

# ---------------------------------------------------------------------------
# Common host paths (mkdir is idempotent; chmod is set defensively)
# ---------------------------------------------------------------------------
mkdir -p /var/log/whp
mkdir -p /var/lib/whp

mkdir -p /var/lib/whp/cpanel-imports
chmod 700 /var/lib/whp/cpanel-imports

mkdir -p /var/lib/whp/bulk-sites
chmod 700 /var/lib/whp/bulk-sites

mkdir -p /docker/whp/sql/bulk-jobs
chmod 750 /docker/whp/sql/bulk-jobs

# Defensive — these ReadWritePaths targets may not exist on a brand new VM
mkdir -p /docker/users
mkdir -p /docker/powerdns/logs
mkdir -p /etc/letsencrypt
mkdir -p /etc/httpd/conf.d

NEED_DAEMON_RELOAD=0

install_unit() {
    local unit_name="$1"
    local src dst
    dst="/etc/systemd/system/$unit_name"

    if ! src="$(resolve_unit_src "$unit_name")"; then
        echo "[$unit_name] source unit file not found in tarball or /root/whp/configs/ — skipping"
        return 0
    fi

    # Idempotency: if dst already exists and matches src, no-op
    if [ -f "$dst" ] && cmp -s "$src" "$dst"; then
        echo "[$unit_name] already installed and current ($dst)"
        return 0
    fi

    echo "[$unit_name] installing from $src"
    cp "$src" "$dst"
    chmod 644 "$dst"
    NEED_DAEMON_RELOAD=1

    if command -v systemd-analyze >/dev/null 2>&1; then
        # Non-fatal: warnings about unknown properties on older systemd are OK
        systemd-analyze verify "$dst" >/dev/null 2>&1 \
            || echo "[$unit_name] systemd-analyze reported warnings (non-fatal)"
    fi
}

install_unit "whp-cpanel-import@.service"
install_unit "whp-bulk-sites@.service"

if [ "$NEED_DAEMON_RELOAD" -eq 1 ]; then
    systemctl daemon-reload
    echo "[systemd] daemon-reload done"
else
    echo "[systemd] no changes — daemon-reload not needed"
fi

# ---------------------------------------------------------------------------
# Logrotate (idempotent overwrites — same content as the original feature
# scripts, restated here so this single script is self-contained)
# ---------------------------------------------------------------------------
write_logrotate() {
    local conf_path="$1"
    local glob_pattern="$2"
    local tmp
    tmp="$(mktemp)"
    cat > "$tmp" <<LR_EOF
${glob_pattern} {
    weekly
    rotate 4
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}
LR_EOF
    if [ -f "$conf_path" ] && cmp -s "$tmp" "$conf_path"; then
        rm -f "$tmp"
        return 0
    fi
    mv "$tmp" "$conf_path"
    chmod 644 "$conf_path"
    echo "[logrotate] wrote $conf_path"
}

write_logrotate "/etc/logrotate.d/whp-cpanel-import" "/var/log/cpanel-import-*.log"
write_logrotate "/etc/logrotate.d/whp-bulk-sites"    "/var/log/whp-bulk-sites-*.log"

echo "=== systemd worker units installed ==="
echo ""
echo "Verify with:"
echo "  systemctl cat whp-cpanel-import@.service"
echo "  systemctl cat whp-bulk-sites@.service"
