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

###############################################################################
# setup-delete-user-worker.sh
#
# Installs the whp-delete-user@.service systemd unit and primes the host
# paths the unit's ProtectSystem=strict / ReadWritePaths sandbox requires.
#
# Background: the panel's delete-user endpoint used to run UserResourceTeardown
# inline, blocking the HTTP request for ~50-60s for a user with several sites
# and many DBs. That crossed Apache's mod_proxy_fcgi default 60s timeout —
# the browser saw ERR_INCOMPLETE_CHUNKED_ENCODING even though the back-end
# completed. The async-fork worker lets the panel return 202 immediately
# and a JSONL progress stream drives a modal.
#
# Pattern mirrors setup-bulk-sites-worker.sh (2026.05.197) and
# setup-cpanel-import-isolation.sh (2026.05.183).
#
# Idempotent.
###############################################################################

echo "=== Setting up WHP delete-user worker isolation ==="

# ---------------------------------------------------------------------------
# 1. Pre-create writable host paths the unit expects to exist
# ---------------------------------------------------------------------------
echo "[paths] Ensuring writable host paths exist..."
mkdir -p /var/log/whp
mkdir -p /var/lib/whp
mkdir -p /var/lib/whp/delete-user
chmod 700 /var/lib/whp/delete-user

mkdir -p /docker/whp/sql/delete-user-jobs
chmod 750 /docker/whp/sql/delete-user-jobs

# Defensive — these exist on a real WHP install but a fresh test VM may not
# have them yet, and a missing ReadWritePaths target is a unit-start failure.
mkdir -p /docker/users
mkdir -p /docker/powerdns/logs
mkdir -p /etc/letsencrypt
mkdir -p /etc/httpd/conf.d
mkdir -p /var/spool/mail
mkdir -p /var/log

echo "[paths] Done."

# ---------------------------------------------------------------------------
# 2. Install the systemd template unit
#
# Resolve the source via $BASH_SOURCE-relative path into the tarball's
# configs/ dir. update.sh runs per-version scripts BEFORE rsyncing
# configs/, so /root/whp/configs/ holds the PREVIOUS release's tree at
# this point — sourcing from there silently installs a stale (or missing)
# unit. See feedback_update_sh_pre_rsync_script_trap.
# ---------------------------------------------------------------------------
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Layout in the extracted tarball:
#   <TARBALL>/scripts/updates/<VERSION>/setup-delete-user-worker.sh
#   <TARBALL>/configs/whp-delete-user@.service
TARBALL_ROOT="$( cd "${SCRIPT_DIR}/../../.." && pwd )"
SERVICE_SRC="${TARBALL_ROOT}/configs/whp-delete-user@.service"
SERVICE_DST="/etc/systemd/system/whp-delete-user@.service"

if [ ! -f "$SERVICE_SRC" ]; then
    # Don't exit 0 silently — the cpanel-import sandbox sat broken for 14
    # days on whp01+whp02 because an earlier setup script did that.
    echo "[systemd] FATAL: expected service file at $SERVICE_SRC but it is missing."
    echo "[systemd] This means the release tarball is malformed or the per-version"
    echo "[systemd] script is being run from an unexpected location."
    exit 1
fi

echo "[systemd] Installing $SERVICE_DST from $SERVICE_SRC..."
cp "$SERVICE_SRC" "$SERVICE_DST"
chmod 644 "$SERVICE_DST"

if command -v systemd-analyze >/dev/null 2>&1; then
    echo "[systemd] Validating unit file..."
    if ! systemd-analyze verify "$SERVICE_DST" 2>&1 | tee /tmp/whp-delete-user-verify.out; then
        echo "[systemd] WARNING: systemd-analyze verify reported issues; review /tmp/whp-delete-user-verify.out"
    fi
fi

systemctl daemon-reload
echo "[systemd] Done."

# ---------------------------------------------------------------------------
# 3. Smoke-test: load the unit and check for fatal config errors
# ---------------------------------------------------------------------------
echo "[systemd] Smoke-testing unit load..."
if systemctl cat whp-delete-user@.service >/dev/null 2>&1; then
    echo "[systemd] Unit loaded cleanly."
else
    echo "[systemd] WARNING: unit did not load cleanly. Run:"
    echo "          systemctl cat whp-delete-user@.service"
    echo "          journalctl -xe"
fi

# ---------------------------------------------------------------------------
# 4. Logrotate for the per-job log files
# ---------------------------------------------------------------------------
LOGROTATE_CONF="/etc/logrotate.d/whp-delete-user"
echo "[logrotate] Writing ${LOGROTATE_CONF}..."
cat > "$LOGROTATE_CONF" <<'LOGROTATE_EOF'
/var/log/whp-delete-user-*.log {
    weekly
    rotate 4
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}
LOGROTATE_EOF
echo "[logrotate] Done."

echo "=== delete-user worker isolation setup complete ==="
echo ""
echo "Verify with:"
echo "  systemctl cat whp-delete-user@.service"
echo "  ls -la /docker/whp/sql/delete-user-jobs/"
echo "  ls -la /var/lib/whp/delete-user/"
