#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  check_rpki_client_ccr.sh \
    --rpki-client <path> \
    --ccr-root <directory-or-ccr-file> \
    --out <result.jsonl> \
    [--limit <count>]

Runs the supplied rpki-client importer against CCR files. A non-zero result
means that rpki-client reported a CCR-file parsing error or could not start.
Per-file command output is retained next to the JSONL result file.
EOF
}

RPKI_CLIENT=""
CCR_ROOT=""
OUT=""
LIMIT=0

while [[ $# -gt 0 ]]; do
  case "$1" in
    --rpki-client) RPKI_CLIENT=${2:?missing value for --rpki-client}; shift 2 ;;
    --ccr-root) CCR_ROOT=${2:?missing value for --ccr-root}; shift 2 ;;
    --out) OUT=${2:?missing value for --out}; shift 2 ;;
    --limit) LIMIT=${2:?missing value for --limit}; shift 2 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "error: unknown argument: $1" >&2; usage >&2; exit 2 ;;
  esac
done

[[ -n "$RPKI_CLIENT" && -n "$CCR_ROOT" && -n "$OUT" ]] || {
  echo "error: --rpki-client, --ccr-root, and --out are required" >&2
  usage >&2
  exit 2
}
[[ -x "$RPKI_CLIENT" ]] || { echo "error: rpki-client is not executable: $RPKI_CLIENT" >&2; exit 2; }
[[ "$LIMIT" =~ ^[0-9]+$ ]] || { echo "error: --limit must be a non-negative integer" >&2; exit 2; }

mkdir -p "$(dirname "$OUT")"
LOG_DIR="${OUT%.jsonl}.logs"
mkdir -p "$LOG_DIR"
: > "$OUT"

declare -a CCR_FILES=()
if [[ -f "$CCR_ROOT" ]]; then
  CCR_FILES=("$(readlink -f "$CCR_ROOT")")
elif [[ -d "$CCR_ROOT" ]]; then
  while IFS= read -r -d '' file; do
    CCR_FILES+=("$file")
  done < <(find "$CCR_ROOT" -type f -name '*.ccr' -print0 | sort -z)
else
  echo "error: CCR root does not exist: $CCR_ROOT" >&2
  exit 2
fi

if (( LIMIT > 0 && ${#CCR_FILES[@]} > LIMIT )); then
  CCR_FILES=("${CCR_FILES[@]:0:LIMIT}")
fi
if (( ${#CCR_FILES[@]} == 0 )); then
  echo "error: no .ccr files found under: $CCR_ROOT" >&2
  exit 2
fi

passed=0
failed=0
for ccr in "${CCR_FILES[@]}"; do
  digest=$(sha256sum "$ccr" | awk '{print $1}')
  log="$LOG_DIR/${digest}.log"
  set +e
  "$RPKI_CLIENT" -f "$ccr" >"$log" 2>&1
  exit_code=$?
  set -e

  classification=pass
  if (( exit_code != 0 )); then
    classification=tool_error
  elif grep -Fq "rpki-client: ${ccr}:" "$log"; then
    classification=ccr_parse_error
  fi
  if [[ "$classification" == pass ]]; then
    ((passed += 1))
  else
    ((failed += 1))
  fi

  python3 - "$OUT" "$ccr" "$digest" "$exit_code" "$classification" "$log" <<'PY'
import json
import sys

out, ccr, sha256, exit_code, classification, log = sys.argv[1:]
with open(out, "a", encoding="utf-8") as stream:
    stream.write(json.dumps({
        "ccr": ccr,
        "sha256": sha256,
        "rpkiClientExitCode": int(exit_code),
        "classification": classification,
        "log": log,
    }, ensure_ascii=False, sort_keys=True) + "\n")
PY
done

echo "checked=${#CCR_FILES[@]} passed=${passed} failed=${failed} jsonl=${OUT} logs=${LOG_DIR}"
(( failed == 0 ))
