#!/usr/bin/env bash
# onx-cert-revoke — Revoke a Let's Encrypt certificate via acme.sh.
# Also removes the installed cert files from /etc/letsencrypt/live/<domain>/.
#
# Input (stdin JSON):
#   domain  string  Domain whose cert to revoke
#
# Output (stdout JSON):
#   {"revoked":true, "domain":..., "files_removed":...}
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=exec-fail
#
# Deployed to: /usr/local/onoxsoft/bin/onx-cert-revoke

set -euo pipefail

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

# ── Constants ────────────────────────────────────────────────────────────────
export LE_WORKING_DIR="/etc/onoxsoft/acme.sh"
ACME_BIN="${LE_WORKING_DIR}/acme.sh"
ACME_CERT_BASE="/etc/letsencrypt/live"

# ── Read & parse stdin ───────────────────────────────────────────────────────
INPUT=$(cat)

onx_require_json "${INPUT}"

DOMAIN=$(onx_json_get "${INPUT}" "domain")

# ── Input validation ─────────────────────────────────────────────────────────
onx_validate_domain "${DOMAIN}"

# ── Preflight ────────────────────────────────────────────────────────────────
[[ -f "${ACME_BIN}" && -x "${ACME_BIN}" ]] || \
  onx_die 2 "acme.sh not found: ${ACME_BIN}"

CERT_INSTALL_DIR="${ACME_CERT_BASE}/${DOMAIN}"
CERT_FILE="${CERT_INSTALL_DIR}/fullchain.pem"

if [[ ! -f "${CERT_FILE}" ]]; then
  # Idempotent: already gone
  onx_log "Certificate not found (already revoked?): ${CERT_FILE}"
  onx_json_out "revoked" "true" "domain" "${DOMAIN}" "files_removed" "false" "note" "already_absent"
  exit 0
fi

# ── Revoke ───────────────────────────────────────────────────────────────────
mkdir -p "/var/log/onoxsoft"

onx_log "Revoking certificate for: ${DOMAIN}"

if ! "${ACME_BIN}" --revoke -d "${DOMAIN}" 2>&1 \
    | tee -a "/var/log/onoxsoft/acme-${DOMAIN}.log"; then
  onx_die 3 "acme.sh --revoke failed for ${DOMAIN}"
fi

# Remove the certificate entry from acme.sh tracking
"${ACME_BIN}" --remove -d "${DOMAIN}" 2>/dev/null || \
  onx_log "WARNING: acme.sh --remove failed (continuing)"

# ── Remove installed cert files ───────────────────────────────────────────────
FILES_REMOVED="false"
if [[ -d "${CERT_INSTALL_DIR}" ]]; then
  rm -rf "${CERT_INSTALL_DIR}"
  FILES_REMOVED="true"
fi

# ── Reload Apache to drop the revoked cert from memory ───────────────────────
systemctl reload httpd 2>/dev/null || true

# ── Success ──────────────────────────────────────────────────────────────────
onx_json_out \
  "revoked"       "true" \
  "domain"        "${DOMAIN}" \
  "files_removed" "${FILES_REMOVED}"
