#!/usr/bin/env bash
# =============================================================================
# onx-gpg-key-export — Export armored public (or secret) key
#
# Input:
#   {
#     "username":    "onx_xxxx",
#     "fingerprint": "AABBCC...",
#     "kind":        "public" | "secret"   // default public
#   }
#
# Output:
#   { "fingerprint":"...", "armor": "-----BEGIN PGP ...", "kind":"public|secret" }
#
# Exit codes: 0=ok 1=invalid-input 2=preflight-fail 3=execution-fail
# Deployed to: /usr/local/onoxsoft/bin/onx-gpg-key-export
# =============================================================================

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")
KIND=$(onx_json_get     "${INPUT}" "kind" "public")

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:]')

case "${KIND}" in
    public|secret) : ;;
    *) onx_die 1 "kind must be 'public' or 'secret'" ;;
esac

id "${USERNAME}" &>/dev/null || onx_die 2 "Linux user does not exist: ${USERNAME}"
GNUPGHOME="/home/${USERNAME}/.gnupg"
[[ -d "${GNUPGHOME}" ]] || onx_die 2 "keyring missing for ${USERNAME}"

if [[ "${KIND}" == "secret" ]]; then
    ARMOR=$(su -s /bin/bash "${USERNAME}" -c \
        "gpg --homedir '${GNUPGHOME}' --armor --export-secret-keys '${FPR_UPPER}'" \
        2>/dev/null || true)
else
    ARMOR=$(su -s /bin/bash "${USERNAME}" -c \
        "gpg --homedir '${GNUPGHOME}' --armor --export '${FPR_UPPER}'" \
        2>/dev/null || true)
fi

[[ -n "${ARMOR}" ]] || onx_die 3 "export returned empty (key missing or locked)"

ARMOR_J=$(printf '%s' "${ARMOR}" | jq -Rs '.')
onx_log "gpg-key-export: ${FPR_UPPER} kind=${KIND} for ${USERNAME}"
printf '{"fingerprint":"%s","armor":%s,"kind":"%s"}\n' "${FPR_UPPER}" "${ARMOR_J}" "${KIND}"
