#!/usr/bin/env bash
# =============================================================================
# onx-gpg-key-delete — Delete a key from a user's ~/.gnupg
#
# Input:  { "username": "onx_xxxx", "fingerprint": "AABBCC...40hex" }
# Output: { "fingerprint":"...", "deleted": true|false }
#
# Behaviour: drops both secret and public components.
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=execution-fail
# Deployed to: /usr/local/onoxsoft/bin/onx-gpg-key-delete
# =============================================================================

set -euo pipefail

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

require_cmd jq
require_cmd gpg

INPUT=$(cat)
onx_require_json "${INPUT}"

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

onx_validate_username "${USERNAME}"
[[ "${FPR}" =~ ^[A-Fa-f0-9]{40}$ ]] || onx_die 1 "fingerprint must be 40 hex chars"
FPR_UPPER=$(echo "${FPR}" | tr '[:lower:]' '[:upper:]')

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

GNUPGHOME="/home/${USERNAME}/.gnupg"

if [[ ! -d "${GNUPGHOME}" ]]; then
    printf '{"fingerprint":"%s","deleted":false,"note":"keyring missing"}\n' "${FPR_UPPER}"
    exit 0
fi

# Probe: does the key exist?
EXISTS=$(su -s /bin/bash "${USERNAME}" -c \
    "gpg --homedir '${GNUPGHOME}' --list-keys --with-colons '${FPR_UPPER}' 2>/dev/null" \
    | grep -c '^pub' || true)

if [[ "${EXISTS}" -eq 0 ]]; then
    printf '{"fingerprint":"%s","deleted":false,"note":"not found"}\n' "${FPR_UPPER}"
    exit 0
fi

# Drop secret first (if present), then public. Both batch + yes for non-interactive.
su -s /bin/bash "${USERNAME}" -c \
    "gpg --homedir '${GNUPGHOME}' --batch --yes --pinentry-mode loopback --delete-secret-keys '${FPR_UPPER}'" \
    >/dev/null 2>&1 || true

su -s /bin/bash "${USERNAME}" -c \
    "gpg --homedir '${GNUPGHOME}' --batch --yes --delete-keys '${FPR_UPPER}'" \
    >/dev/null 2>&1 || onx_die 3 "gpg --delete-keys failed for ${FPR_UPPER}"

onx_log "gpg-key-delete: ${FPR_UPPER} from ${USERNAME}"

printf '{"fingerprint":"%s","deleted":true}\n' "${FPR_UPPER}"
