#!/usr/bin/env bash
# =============================================================================
# onx-customer-slice-delete — Remove per-customer systemd slice
#
# v86.1 — Multi-tenant isolation: per-customer slice teardown.
#
# Stops customer-${USERNAME}.slice, removes the unit file, and reloads
# systemd. Idempotent: missing slice → noop with `removed: false`.
#
# Input (stdin JSON):
#   { "username": "onx_leafport" }
#
# Output (stdout JSON):
#   { "ok": true, "username": "...", "slice_unit": "...", "removed": true }
#   { "ok": true, "username": "...", "slice_unit": "...", "removed": false,
#     "reason": "slice unit not present" }
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-customer-slice-delete
# =============================================================================

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
# shellcheck source=_lib/common.sh
source "${SCRIPT_DIR}/_lib/common.sh"

command -v jq        >/dev/null 2>&1 || onx_die 2 "jq required"
command -v systemctl >/dev/null 2>&1 || onx_die 2 "systemctl required"
require_root

# ── Read stdin ───────────────────────────────────────────────────────────────
INPUT="$(cat)"
onx_require_json "${INPUT}"

USERNAME=$(onx_json_get "${INPUT}" "username")

# Widen pattern (consistent with onx-customer-slice-create)
[[ "${USERNAME}" =~ ^onx_[a-z0-9]{4,30}$ ]] \
    || onx_die 1 "invalid username '${USERNAME}': must match ^onx_[a-z0-9]{4,30}\$"

SLICE_UNIT="customer-${USERNAME}.slice"
SLICE_PATH="/etc/systemd/system/${SLICE_UNIT}"
DROPIN_DIR="/etc/systemd/system/${SLICE_UNIT}.d"

# ── Idempotent guard ─────────────────────────────────────────────────────────
if [[ ! -f "${SLICE_PATH}" ]]; then
    onx_log "slice-delete: ${SLICE_UNIT} not present (noop)"
    jq -nc \
        --arg username "${USERNAME}" \
        --arg slice_unit "${SLICE_UNIT}" \
        '{ok:true, username:$username, slice_unit:$slice_unit, removed:false, reason:"slice unit not present"}'
    exit 0
fi

# ── Stop slice (best-effort — slices are aggregators; child procs survive) ───
# Note: stopping a slice does NOT kill the children. Caller is responsible
# for migrating/terminating worker processes first (FPM pool stop, cron purge).
systemctl stop "${SLICE_UNIT}" >/dev/null 2>&1 || true

# Wait a beat for cgroup release
sleep 0.1

# ── Remove unit file + any drop-ins ──────────────────────────────────────────
rm -f "${SLICE_PATH}"
if [[ -d "${DROPIN_DIR}" ]]; then
    # Only remove if directory contains nothing but drop-ins we wrote
    rm -rf "${DROPIN_DIR}"
fi

# ── Reload systemd ───────────────────────────────────────────────────────────
systemctl daemon-reload || onx_die 3 "systemctl daemon-reload failed"

# Clear any failed state so we don't pollute systemctl --failed
systemctl reset-failed "${SLICE_UNIT}" 2>/dev/null || true

onx_log "slice-delete: ${SLICE_UNIT} removed"

jq -nc \
    --arg username "${USERNAME}" \
    --arg slice_unit "${SLICE_UNIT}" \
    --arg slice_path "${SLICE_PATH}" \
    '{ok:true, username:$username, slice_unit:$slice_unit, slice_path:$slice_path, removed:true}'
