#!/usr/bin/env bash
# audit-export.sh - export one project's tamper-proof audit trail from the IndyKite Audit Log API.
#
# Required environment:
#   API_URL     https://eu.api.indykite.com or https://us.api.indykite.com (the project's region)
#   PROJECT_ID  the project GID, gid:...
#   CLIENT_KEY  an Application Agent credential of that project, holding the Audit API permission
#
# Usage: audit-export.sh [output-dir]      default: audit-export/<project>/<UTC timestamp>
#
# Writes:
#   jwks.json                     the JWK Set current at export time
#   jwks-<digest>.json            every JWK Set this project has ever exported (see below)
#   checkpoints/page-NNNN.json    every page of GET /audit/v1/checkpoints, byte for byte
#   manifests/page-NNNN.json      every page of GET /audit/v1/manifests, byte for byte
#   logs/page-NNNN.json           every page of GET /audit/v1/logs, byte for byte
#   manifests.jsonl, logs.jsonl, checkpoints.jsonl   one item per line, for jq
#
# Raw pages are kept because the batch hash covers the data array exactly as served;
# audit-verify.py reads them. The .jsonl files are a convenience and are not what gets verified.
#
# Key rotation: the JWK Set lists every key that has signed for the project, current and retired.
# Every JWK Set fetched is also kept in JWKS_ARCHIVE (default: <parent of output-dir>/jwks-archive),
# and every file in that archive is copied into each export, so each export folder verifies on its
# own, without the API. The set is fetched again after the pages, in case the key rotated meanwhile,
# and the export fails if any kid in the exported records is in none of the saved sets (a new key
# can take up to 2 minutes to be listed, and the JWK Set may be cached for up to 60 seconds, so
# rerun a little later in that case).
#
# Consistency: the three endpoints are read in turn while the chain may still grow. Checkpoints
# are read first, so none can point past the manifests; afterwards whichever of logs and
# manifests is behind is read again until both end at the same sequence.
# Any HTTP error stops the export: a partial export is reported, never silently truncated.
set -euo pipefail

: "${API_URL:?set API_URL}" "${PROJECT_ID:?set PROJECT_ID}" "${CLIENT_KEY:?set CLIENT_KEY}"
command -v jq >/dev/null || {
    echo "jq is required" >&2
    exit 2
}

stamp="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
OUT="${1:-audit-export/${PROJECT_ID#gid:}/${stamp}}"
parent="$(dirname "${OUT}")"
JWKS_ARCHIVE="${JWKS_ARCHIVE:-${parent}/jwks-archive}"
mkdir -p "${OUT}/manifests" "${OUT}/logs" "${OUT}/checkpoints" "${JWKS_ARCHIVE}"

fetch_jwks() { # fetch the current JWK Set, archive it by content digest, copy every archived set into the export
    local kids digest archived
    curl -fsS "${API_URL}/audit/.well-known/jwks.json?project_id=${PROJECT_ID}" -o "${OUT}/jwks.json"
    kids="$(jq -r '[.keys[].kid] | sort | join(", ")' "${OUT}/jwks.json")"
    digest="$(sha256sum "${OUT}/jwks.json" | cut -c1-16)" # named by content, so distinct sets never collide
    [[ -f "${JWKS_ARCHIVE}/jwks-${digest}.json" ]] || cp "${OUT}/jwks.json" "${JWKS_ARCHIVE}/jwks-${digest}.json"
    cp "${JWKS_ARCHIVE}"/jwks-*.json "${OUT}/"
    archived="$(find "${JWKS_ARCHIVE}" -name 'jwks-*.json' | wc -l)"
    echo "keys: ${kids} (${archived} JWK Set(s) kept with the export)"
}

fetch_jwks

fetch_all() { # $1 = logs | manifests | checkpoints
    local endpoint="$1" cursor="" n=0 page has_more items
    rm -f "${OUT}/${endpoint}"/page-*.json
    : >"${OUT}/${endpoint}.jsonl"
    while :; do
        n=$((n + 1))
        page="${OUT}/${endpoint}/page-$(printf '%04d' "${n}").json"
        curl -fsS "${API_URL}/audit/v1/${endpoint}?project_id=${PROJECT_ID}&pagesize=50&cursor=${cursor}" \
            -H "X-IK-ClientKey: ${CLIENT_KEY}" -o "${page}" ||
            {
                echo "export of ${endpoint} failed on page ${n}; ${OUT} is incomplete" >&2
                exit 1
            }
        jq -c '.items[]' "${page}" >>"${OUT}/${endpoint}.jsonl"
        has_more="$(jq -r '.has_more' "${page}")"
        [[ "${has_more}" == "true" ]] || break
        cursor="$(jq -r '.next_cursor' "${page}")"
    done
    items="$(wc -l <"${OUT}/${endpoint}.jsonl")"
    echo "${endpoint}: ${n} page(s), ${items} item(s)"
}

newest_of() { # $1 = manifests | logs
    jq -s 'map(.sequence) | max // 0' "${OUT}/$1.jsonl"
}

fetch_all checkpoints
fetch_all manifests
fetch_all logs
for _ in 1 2 3 4 5; do
    newest_manifest="$(newest_of manifests)"
    newest_log="$(newest_of logs)"
    [[ "${newest_log}" -eq "${newest_manifest}" ]] && break
    if [[ "${newest_log}" -gt "${newest_manifest}" ]]; then
        echo "logs reach sequence ${newest_log}, manifests ${newest_manifest}: reading manifests again"
        fetch_all manifests
    else
        echo "manifests reach sequence ${newest_manifest}, logs ${newest_log}: reading logs again"
        fetch_all logs
    fi
done
newest_manifest="$(newest_of manifests)"
newest_log="$(newest_of logs)"
if [[ "${newest_log}" -ne "${newest_manifest}" ]]; then
    echo "chain still growing: logs at ${newest_log}, manifests at ${newest_manifest}; rerun the export" >&2
    exit 1
fi

# the key may have rotated while the pages were read: fetch the set again, then check that every
# kid the exported records name is in one of the saved sets
fetch_jwks
known_kids="$(jq -s '[.[].keys[].kid] | unique' "${OUT}"/jwks*.json)"
missing_kids="$(jq -cs --argjson known "${known_kids}" '([.[].kid] | unique) - $known' \
    "${OUT}/manifests.jsonl" "${OUT}/logs.jsonl" "${OUT}/checkpoints.jsonl")"
if [[ "${missing_kids}" != "[]" ]]; then
    echo "incomplete export: no saved JWK Set holds the signing keys ${missing_kids}; rerun in a few minutes" >&2
    exit 1
fi

echo "newest sequence: ${newest_manifest}"
echo "export written to ${OUT}"
