#!/usr/bin/env bash
set -euo pipefail
###############################################################################
# reinstall-cpanel-import-unit-docker-whp-rw.sh
#
# Re-copies whp-cpanel-import@.service to /etc/systemd/system/ so the
# updated ReadWritePaths (now including /docker/whp) takes effect on
# existing installs. The 2026.06.9 relocation moved the cpanel-importer
# bind-mount roots to /docker/whp/cpanel-importer-{extract,quarantine}
# but didn't update the worker unit's ReadWritePaths list, leaving
# /docker/whp read-only under ProtectSystem=strict. Worker's mkdir of
# the per-import subdir then failed silently, docker auto-created the
# bind-mount path as root-owned, and the container's uid 999 couldn't
# mkdir inside ("cannot create quarantine/sanitized output dirs").
#
# Resolves the source unit via $BASH_SOURCE-relative path into the
# tarball extract (apply-scripts runs per-version scripts BEFORE the
# configs/ rsync, see feedback_update_sh_pre_rsync_script_trap), with
# a /root/whp/configs fallback for manual re-runs.
#
# Idempotent: cmp-s checks before copying; daemon-reload only fires if
# the unit content actually changed.
###############################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
UNIT_NAME=whp-cpanel-import@.service
DST=/etc/systemd/system/$UNIT_NAME

src=""
for candidate in \
    "$SCRIPT_DIR/../../../configs/$UNIT_NAME" \
    "/root/whp/configs/$UNIT_NAME"; do
    if [ -f "$candidate" ]; then
        src="$candidate"
        break
    fi
done

if [ -z "$src" ]; then
    echo "ERROR: source unit file not found in tarball or /root/whp/configs"
    exit 1
fi

# Also make sure the /docker/whp roots themselves exist with the right
# ownership for the new bind mount targets. setup.sh creates these on
# fresh installs and relocate-cpanel-importer-roots.sh handles them for
# upgrades; this is belt-and-suspenders if either flow was skipped.
mkdir -p /docker/whp/cpanel-importer-extract /docker/whp/cpanel-importer-quarantine
chown 999:999 /docker/whp/cpanel-importer-extract /docker/whp/cpanel-importer-quarantine
chmod 0750 /docker/whp/cpanel-importer-extract /docker/whp/cpanel-importer-quarantine

if [ -f "$DST" ] && cmp -s "$src" "$DST"; then
    echo "[unit] $DST already up to date"
    exit 0
fi

cp "$src" "$DST"
chmod 644 "$DST"
echo "[unit] installed $DST from $src"

systemctl daemon-reload
echo "[unit] daemon-reload done"

# Validate the new unit. Non-fatal warnings about unknown properties on
# older systemd versions are acceptable.
if command -v systemd-analyze >/dev/null 2>&1; then
    systemd-analyze verify "$DST" >/dev/null 2>&1 \
        || echo "[unit] systemd-analyze reported warnings (non-fatal)"
fi
