#!/usr/bin/env bash
# Postgres connector: create the source (vaulted read-only credentials),
# test the connection, first sync. Requires a reachable database (hosted
# runs only, not the local stack): set TESSERA_PG_HOST / TESSERA_PG_DB / TESSERA_PG_TABLE /
# TESSERA_PG_USER / TESSERA_PG_PASSWORD.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"
: "${TESSERA_PG_HOST:?database host}"
: "${TESSERA_PG_DB:?database name}"
: "${TESSERA_PG_TABLE:?table to extract}"
: "${TESSERA_PG_USER:?read-only user}"
: "${TESSERA_PG_PASSWORD:?password}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")

SOURCE="$(curl -sS -X POST "$TESSERA_API_BASE/sources" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-postgres-source" \
  -d '{
    "name": "orders-db",
    "kind": "postgres",
    "config": {
      "host": "'"$TESSERA_PG_HOST"'",
      "database": "'"$TESSERA_PG_DB"'",
      "table": "'"$TESSERA_PG_TABLE"'",
      "ssl_mode": "require"
    },
    "credentials": {
      "username": "'"$TESSERA_PG_USER"'",
      "password": "'"$TESSERA_PG_PASSWORD"'"
    }
  }')"
SOURCE_ID="$(printf '%s' "$SOURCE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["source_id"])')"

# Checks: tcp_or_tunnel, authenticate, table_readable, read_only (warns if
# the user holds write privileges — use a read-only role).
curl -sS -X POST "$TESSERA_API_BASE/sources/$SOURCE_ID/test-connection" "${AUTH[@]}" \
  | python3 -c '
import json, sys
result = json.load(sys.stdin)
print("test-connection:", result["status"])
for check in result["checks"]:
    print("  %s: %s" % (check["name"], check["status"]))
'

SYNC="$(curl -sS -X POST "$TESSERA_API_BASE/sources/$SOURCE_ID/syncs" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-postgres-first-sync" \
  -d '{"mode": "full"}')"
SYNC_ID="$(printf '%s' "$SYNC" | python3 -c 'import json,sys; print(json.load(sys.stdin)["sync_id"])')"
for _ in $(seq 1 600); do
  STATUS="$(curl -sS "$TESSERA_API_BASE/syncs/$SYNC_ID" "${AUTH[@]}" \
    | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
  if [ "$STATUS" = "succeeded" ] || [ "$STATUS" = "failed" ]; then break; fi
  sleep 1
done
echo "first sync: $STATUS"
