#!/usr/bin/env bash
# =============================================================================
# onx-cgroup-clear — Remove onox cgroup limit drop-in for a user
#
# Purpose:
#   Removes /etc/systemd/system/user-${UID}.slice.d/onox-limits.conf and
#   reloads systemd so the user slice reverts to system/package defaults.
#
# Input (stdin JSON):
#   { "username": "onx_xxxx" }
#
# Output (stdout JSON):
#   { "cleared": true, "username": "onx_xxxx", "uid": 1001 }
#   { "cleared": false, "username": "onx_xxxx", "reason": "no override found" }
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-cgroup-clear
# =============================================================================

set -euo pipefail

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

command -v jq        >/dev/null 2>&1 || { printf '{"error":"jq required"}\n' >&2; exit 2; }
command -v systemctl >/dev/null 2>&1 || { printf '{"error":"systemctl required"}\n' >&2; exit 2; }
require_root

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

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

id "${USERNAME}" &>/dev/null || onx_die 2 "Linux user does not exist: ${USERNAME}"

UID_VAL=$(id -u "${USERNAME}")
DROPIN_FILE="/etc/systemd/system/user-${UID_VAL}.slice.d/onox-limits.conf"
DROPIN_DIR="/etc/systemd/system/user-${UID_VAL}.slice.d"

if [[ ! -f "${DROPIN_FILE}" ]]; then
    printf '{"cleared":false,"username":"%s","uid":%s,"reason":"no override found"}\n' \
        "${USERNAME}" "${UID_VAL}"
    exit 0
fi

rm -f "${DROPIN_FILE}"

# Remove directory if now empty
rmdir "${DROPIN_DIR}" 2>/dev/null || true

systemctl daemon-reload || onx_die 3 "systemctl daemon-reload failed"

onx_log "cgroup-clear: ${USERNAME} (uid=${UID_VAL}) override removed"

printf '{"cleared":true,"username":"%s","uid":%s}\n' "${USERNAME}" "${UID_VAL}"
