#!/bin/bash
set -euo pipefail

IMAGE="synapse-backupper:test"

cleanup() {
    docker rm -f sb-pg-test 2>/dev/null || true
    rm -rf tmp-keys tmp-backups tmp-restored
}
trap cleanup EXIT

# 1. Start PostgreSQL
docker run -d --name sb-pg-test -e POSTGRES_PASSWORD=test postgres:17-alpine
# Wait for ready
for i in {1..30}; do
    docker exec sb-pg-test pg_isready -U postgres && break
    sleep 1
done

# 2. Create database
docker exec sb-pg-test psql -U postgres -c "CREATE DATABASE synapse;"

# 3. Create fixture table
docker exec sb-pg-test psql -U postgres -d synapse -c "CREATE TABLE rooms (id serial PRIMARY KEY, name text); INSERT INTO rooms (name) VALUES ('test1');"

# 4. Generate keys
mkdir -p tmp-keys
chmod 777 tmp-keys
docker run --rm -v "$(pwd)/tmp-keys:/keys" "$IMAGE" keygen --type both --out-prefix /keys/test

# 5. Run backup
mkdir -p tmp-backups
chmod 777 tmp-backups
docker run --rm --network container:sb-pg-test \
    -v "$(pwd)/tmp-keys:/keys:ro" \
    -v "$(pwd)/tmp-backups:/backups" \
    -e APP_PG_HOST=127.0.0.1 \
    -e APP_PG_USER=postgres \
    -e APP_PG_PASSWORD=test \
    -e APP_PG_DATABASE=synapse \
    -e APP_PQ_PUBLIC_KEY_PATH=/keys/test.pq.pub.pem \
    -e APP_CLASSICAL_PUBLIC_KEY_PATH=/keys/test.classical.pub.pem \
    -e APP_BACKUP_DIR=/backups \
    "$IMAGE" backup

# 6. Assert exactly ONE .pqenc file
PQENC_COUNT=$(ls tmp-backups/*.pqenc 2>/dev/null | wc -l)
if [ "$PQENC_COUNT" -ne 1 ]; then
    echo "Expected exactly 1 .pqenc file, found $PQENC_COUNT"
    exit 1
fi
PQENC_FILE=$(ls tmp-backups/*.pqenc)

# 7. Restore
mkdir -p tmp-restored
chmod 777 tmp-restored
docker run --rm \
    -v "$(pwd)/tmp-keys:/keys:ro" \
    -v "$(pwd)/tmp-backups:/backups:ro" \
    -v "$(pwd)/tmp-restored:/out" \
    "$IMAGE" restore \
    --in "/backups/$(basename "$PQENC_FILE")" \
    --privkey-pq /keys/test.pq.priv.pem \
    --privkey-classical /keys/test.classical.priv.pem \
    --out /out/restored.dump

# 8. Assert restore dump contains rooms table
grep -q "CREATE TABLE public.rooms" tmp-restored/restored.dump

echo "Integration test PASSED"
