#!/usr/bin/env bash
# =============================================================================
# onx-user-unsuspend — Restore a suspended hosting account
#
# Purpose:
#   Unlocks Linux password, restores shell to /bin/bash, re-enables Apache
#   vhosts by moving config files back from suspended/, and removes the
#   suspension.json marker file.
#
# Input (stdin JSON):
#   {
#     "username": "onx_xxxx"    -- required
#   }
#
# Output (stdout JSON):
#   {"username":..., "status":"active", "unsuspended_at":"<ISO8601>"}
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail 4=rolled-back 5=rollback-failed
#
# Sudoers entry needed:
#   apache ALL=(root) NOPASSWD: /usr/local/onoxsoft/bin/onx-user-unsuspend
#   Defaults!/usr/local/onoxsoft/bin/onx-user-unsuspend !requiretty
#   Defaults!/usr/local/onoxsoft/bin/onx-user-unsuspend log_output, log_input
#
# Deployed to: /usr/local/onoxsoft/bin/onx-user-unsuspend
# =============================================================================

set -euo pipefail

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

# ── Constants ─────────────────────────────────────────────────────────────────
VHOST_ACTIVE_DIR="/etc/httpd/conf.d/sites"
VHOST_SUSPENDED_DIR="/etc/httpd/suspended"
META_DIR=".onox"
ACTIVE_SHELL="/bin/bash"

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

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

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

# ── Input validation ──────────────────────────────────────────────────────────
onx_validate_username "${USERNAME}"

# ── Preflight ─────────────────────────────────────────────────────────────────
id "${USERNAME}" &>/dev/null           || onx_die 2 "Linux user does not exist: ${USERNAME}"
[[ -d "${VHOST_SUSPENDED_DIR}" ]]      || onx_die 2 "suspended vhost dir not found: ${VHOST_SUSPENDED_DIR}"
[[ -d "${VHOST_ACTIVE_DIR}" ]]         || onx_die 2 "active vhost dir not found: ${VHOST_ACTIVE_DIR}"

trap 'onx_rollback_run' ERR

# ── Unlock password ───────────────────────────────────────────────────────────
usermod -U "${USERNAME}"
onx_rollback_register "usermod -L '${USERNAME}' 2>/dev/null || true"
onx_log "password unlocked: ${USERNAME}"

# ── Restore shell ─────────────────────────────────────────────────────────────
usermod -s "${ACTIVE_SHELL}" "${USERNAME}"
onx_rollback_register "usermod -s /sbin/nologin '${USERNAME}' 2>/dev/null || true"
onx_log "shell restored to ${ACTIVE_SHELL}: ${USERNAME}"

# ── Move vhost configs back to active sites/ ──────────────────────────────────
VHOSTS_RESTORED=()
for conf in "${VHOST_SUSPENDED_DIR}/${USERNAME}"-*.conf; do
    [[ -f "$conf" ]] || continue
    mv "$conf" "${VHOST_ACTIVE_DIR}/"
    VHOSTS_RESTORED+=("$(basename "$conf")")
    onx_log "vhost restored: $conf"
done
# Register rollback: move them back to suspended
for f in "${VHOSTS_RESTORED[@]+"${VHOSTS_RESTORED[@]}"}"; do
    onx_rollback_register "mv '${VHOST_ACTIVE_DIR}/${f}' '${VHOST_SUSPENDED_DIR}/' 2>/dev/null || true"
done

# ── Reload Apache ─────────────────────────────────────────────────────────────
systemctl reload httpd || onx_die 3 "systemctl reload httpd failed"
onx_log "httpd reloaded after unsuspend of ${USERNAME}"

# ── Remove suspension marker ──────────────────────────────────────────────────
SUSPENSION_FILE="/home/${USERNAME}/${META_DIR}/suspension.json"
[[ -f "${SUSPENSION_FILE}" ]] && rm -f "${SUSPENSION_FILE}"
onx_log "suspension.json removed"

# ── Output ────────────────────────────────────────────────────────────────────
UNSUSPENDED_AT=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
onx_json_out \
    "username"       "${USERNAME}" \
    "status"         "active" \
    "unsuspended_at" "${UNSUSPENDED_AT}"
