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

###############################################################################
# setup-cpanel-importer-sandbox.sh
#
# Provisions an existing WHP host for the cPanel import sanitization sandbox:
#
#   1. Creates the host bind-mount roots the docker run needs:
#        /var/lib/whp/cpanel-importer-extract     (mode 0750)
#        /var/lib/whp/cpanel-importer-quarantine  (mode 0750)
#
#   2. Pulls the cpanel-importer image (best-effort). The image lives in the
#      WHP registry at repo.anhonesthost.net/cloud-hosting-platform/cpanel-importer.
#      On early deploys (before the image is published) the pull fails and we
#      log a warning - the panel falls back to direct mode on the next import.
#
#   3. Writes a logrotate rule for the per-import container stdout/stderr
#      capture that the panel writes into the worker's importLog.
#
# Why a separate staging script:
#   - setup.sh handles fresh installs (we extend its container_types pre-pull
#     block in a separate "infrastructure images" pass).
#   - This script covers existing-server upgrades. Per CLAUDE.md and
#     /workspace/whp/CLAUDE.md, /root/whp/configs/ is NOT current when
#     apply-scripts.sh runs - we don't actually need any files from configs/
#     here, so the BASH_SOURCE-relative pattern is unused but the script
#     still uses an absolute-paths-only style per shell-script requirements.
#
# Idempotent. Safe to re-run.
###############################################################################

echo "=== Setting up cPanel import sanitization sandbox ==="

# ---------------------------------------------------------------------------
# 1. Host bind-mount directories
# ---------------------------------------------------------------------------
EXTRACT_ROOT=/var/lib/whp/cpanel-importer-extract
QUARANTINE_ROOT=/var/lib/whp/cpanel-importer-quarantine

echo "[paths] Ensuring sandbox bind-mount roots exist..."
mkdir -p "$EXTRACT_ROOT" "$QUARANTINE_ROOT"
chmod 0750 "$EXTRACT_ROOT" "$QUARANTINE_ROOT"

# These dirs hold per-import subdirs that the docker run mounts in. Owned
# by root because the worker (whp-cpanel-import@.service) runs as root and
# the container side reads/writes via UID 999, mapped through a tmpfs.
# Leaving the ownership at root:root keeps host-side enumeration root-only.
echo "[paths] Done."

# ---------------------------------------------------------------------------
# 2. Image pre-pull (best-effort)
# ---------------------------------------------------------------------------
IMAGE_DEFAULT=repo.anhonesthost.net/cloud-hosting-platform/cpanel-importer:latest

# Read the configured image from settings.json so an operator who has pinned
# a specific tag gets that tag pulled. Falls back to the default when the
# settings.json hasn't been seeded yet (seed-cpanel-import-settings.sh) or
# the cpanel_import block is missing the image key.
CONFIGURED_IMAGE=""
if [ -f /docker/whp/settings.json ] && command -v jq >/dev/null 2>&1; then
    CONFIGURED_IMAGE=$(jq -r '.cpanel_import.image // empty' /docker/whp/settings.json 2>/dev/null || true)
fi
IMAGE="${CONFIGURED_IMAGE:-$IMAGE_DEFAULT}"

echo "[image] Pre-pulling $IMAGE (best-effort)..."
if command -v docker >/dev/null 2>&1; then
    if docker pull "$IMAGE" >/dev/null 2>&1; then
        echo "[image]   pulled OK"
    else
        echo "[image]   WARN: pull failed - image may not be in registry yet."
        echo "[image]   The panel will fall back to direct mode on import until"
        echo "[image]   the image is available. Toggle off 'fall_back_to_direct'"
        echo "[image]   in Server Settings -> Security to make this a hard error."
    fi
else
    echo "[image]   WARN: docker CLI not present - skipping image pull."
fi

# ---------------------------------------------------------------------------
# 3. logrotate for the per-import container output capture
#
# The panel writes container stdout/stderr into whp.cpanel_imports.log via
# CpanelImportSanitizationContainer::runSanitization()'s line-streamer; that
# rotates with the DB row. The systemd unit's StandardOutput=append:/var/log/
# cpanel-import-<id>.log is already covered by setup-cpanel-import-isolation.sh.
# Nothing new to install here, but we leave this section as a marker so a
# future image variant that also writes a host-side container log knows
# where the rotate config would live.
# ---------------------------------------------------------------------------
# (intentionally empty for now - see comment above)

# ---------------------------------------------------------------------------
# 4. Smoke-test: confirm the image runs and reports a version. We do not
#    spawn a real import; just confirm the entrypoint is callable. Tolerant
#    of a missing image since the pre-pull above may have failed.
# ---------------------------------------------------------------------------
echo "[smoke] Smoke-testing container image..."
if command -v docker >/dev/null 2>&1 && docker image inspect "$IMAGE" >/dev/null 2>&1; then
    # The container scaffold's entrypoint.sh exits with rc=1 if the required
    # env vars are missing. That's a sufficient "the image runs" probe.
    set +e
    docker run --rm --network none --user 999:999 --cap-drop=ALL --read-only \
        --tmpfs /tmp:size=8m "$IMAGE" --version >/dev/null 2>&1
    rc=$?
    set -e
    if [ $rc -eq 0 ] || [ $rc -eq 1 ] || [ $rc -eq 2 ]; then
        echo "[smoke]   image entrypoint is callable (rc=$rc)"
    else
        echo "[smoke]   WARN: image smoke-run returned unexpected rc=$rc"
    fi
else
    echo "[smoke]   image not present locally; skipping smoke-test"
fi

echo "=== cPanel import sandbox setup complete ==="
echo ""
echo "Operator next steps:"
echo "  1. Confirm the image is pulled: docker images | grep cpanel-importer"
echo "  2. Server Settings -> Security -> 'cPanel Import: Sanitization Sandbox'"
echo "     to flip execution_mode from 'direct' to 'sanitization-container'."
echo "  3. Run a test import on a small cpmove tarball before changing the"
echo "     default for production traffic."
