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

###############################################################################
# setup-bulk-sites-worker.sh
#
# Installs the whp-bulk-sites@.service systemd unit and primes the host paths
# the unit's ProtectSystem=strict / ReadWritePaths sandbox requires.
#
# Background: the multi-site bulk-management endpoint (api/sites-bulk.php)
# used to run the per-site work inline, blocking the HTTP request for up to
# N x per-op duration. With WHP_BULK_MAX_SITES = 200 and per-op durations
# that can hit ~30s (container recreate, SSL renew), the inline path
# trivially exceeded php-fpm/proxy idle timeouts. This unit lets the panel
# return 202 immediately and the JSONL progress stream drive the UI.
#
# Pattern mirrors setup-cpanel-import-isolation.sh (2026.05.183).
#
# Idempotent.
###############################################################################

echo "=== Setting up WHP bulk-sites worker isolation ==="

# ---------------------------------------------------------------------------
# 1. Pre-create writable host paths the unit expects to exist
#
# ProtectSystem=strict + ReadWritePaths= bind-mounts each listed path into
# the service mount namespace; if any path is missing the unit fails to
# start. Idempotent mkdir keeps this safe to re-run.
# ---------------------------------------------------------------------------
echo "[paths] Ensuring writable host paths exist..."
mkdir -p /var/log/whp
mkdir -p /var/lib/whp
mkdir -p /var/lib/whp/bulk-sites
chmod 700 /var/lib/whp/bulk-sites

# Per-job JSONL stream and spec JSON live here. The HTTP endpoint also
# creates this dir on-demand via the whp_bulk_job_dir() helper, but having
# it owned by root with mode 0750 from staging keeps customer code (which
# runs in containers under per-user uids) from being able to read other
# customers' job specs via accidental symlink traversal.
mkdir -p /docker/whp/sql/bulk-jobs
chmod 750 /docker/whp/sql/bulk-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/log

echo "[paths] Done."

# ---------------------------------------------------------------------------
# 2. Install the systemd template unit
# ---------------------------------------------------------------------------
SERVICE_SRC="/root/whp/configs/whp-bulk-sites@.service"
SERVICE_DST="/etc/systemd/system/whp-bulk-sites@.service"

if [ ! -f "$SERVICE_SRC" ]; then
    echo "[systemd] $SERVICE_SRC not yet synced (update.sh rsyncs configs AFTER per-version scripts)."
    echo "[systemd] Falling through; endpoint's legacy-fallback path will spawn the worker without sandbox until re-run."
    echo "=== bulk-sites worker isolation deferred ==="
    exit 0
fi

echo "[systemd] Installing $SERVICE_DST..."
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-bulk-sites-verify.out; then
        echo "[systemd] WARNING: systemd-analyze verify reported issues; review /tmp/whp-bulk-sites-verify.out"
        # Non-fatal: warnings about unknown properties on older systemd are OK.
        # If the unit truly fails to load, daemon-reload below will surface it.
    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-bulk-sites@.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-bulk-sites@.service"
    echo "          journalctl -xe"
fi

# ---------------------------------------------------------------------------
# 4. Logrotate for the per-job log files
#
# The unit writes /var/log/whp-bulk-sites-<job_id>.log via
# StandardOutput=append:. Old logs accumulate one file per job; rotate by
# age so the directory does not grow unbounded under heavy bulk usage.
# ---------------------------------------------------------------------------
LOGROTATE_CONF="/etc/logrotate.d/whp-bulk-sites"
echo "[logrotate] Writing ${LOGROTATE_CONF}..."
cat > "$LOGROTATE_CONF" <<'LOGROTATE_EOF'
/var/log/whp-bulk-sites-*.log {
    weekly
    rotate 4
    compress
    delaycompress
    missingok
    notifempty
    copytruncate
}
LOGROTATE_EOF
echo "[logrotate] Done."

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