#!/usr/bin/env bash
# Requires curl + jq. Secrets are environment variables, not source literals.
set -euo pipefail
: "${REDACTTOOL_BASE_URL:?Set service URL}"
: "${REDACTTOOL_API_KEY:?Set trial key}"
: "${REDACTTOOL_FILE:?Set input file}"
case "$REDACTTOOL_BASE_URL" in https://*|http://localhost:*|http://127.0.0.1:*) ;; *) test "${REDACTTOOL_ALLOW_HTTP_TRIAL:-0}" = 1 || { echo 'Use HTTPS or explicitly allow fictional HTTP trial'; exit 1; };; esac
base=${REDACTTOOL_BASE_URL%/}
# curl reads authentication from stdin rather than a command-line argument.
auth(){ printf 'header = "Authorization: Bearer %s"\n' "$REDACTTOOL_API_KEY"; }
file_id=$(auth | curl --config - --fail --silent --show-error --max-time 120 -F "file=@${REDACTTOOL_FILE}" "$base/v1/files" | jq -er .file_id)
request_id="$(date +%s)-${RANDOM}-${RANDOM}"
printf 'Keep file_id=%s and Idempotency-Key=%s for recovery\n' "$file_id" "$request_id"
body=$(jq -nc --arg f "$file_id" '{file_id:$f,mode:"placeholder"}')
job=$(auth | curl --config - --fail --silent --show-error --max-time 60 -H 'Content-Type: application/json' -H "Idempotency-Key: $request_id" -d "$body" "$base/v1/redactions")
id=$(printf '%s' "$job" | jq -er .id)
printf 'Job: %s\n' "$id"
for ((attempt=0;attempt<900;attempt++)); do
 status=$(printf '%s' "$job" | jq -r .status)
 case "$status" in completed) break;; failed) printf '%s' "$job" | jq '{status,error}'; exit 1;; esac
 sleep 4
 job=$(auth | curl --config - --fail --silent --show-error --retry 3 --max-time 60 "$base/v1/redactions/$id")
done
[[ $(printf '%s' "$job" | jq -r .status) == completed ]] || { echo 'Deadline reached; resume polling the same job'; exit 1; }
output="${REDACTTOOL_FILE%.*}-redacted.${REDACTTOOL_FILE##*.}"
[[ ! -e "$output" ]] || { echo 'Output exists; choose another input filename'; exit 1; }
auth | curl --config - --fail --silent --show-error --retry 3 --max-time 120 "$base/v1/redactions/$id/file" -o "$output"
printf 'Saved: %s\n' "$output"
