#!/usr/bin/env bash
# Drill restore logis end-to-end: backup, jatuhkan, pulihkan, bandingkan.
set -euo pipefail

DB_LATIHAN=probe_drill_bk7
BERKAS=/tmp/pgtutor-drill/logis.dump
PENGECEKAN="SELECT md5(string_agg(id::text || ':' || item || ':' || jumlah::text, ',' ORDER BY id)) FROM penjualan;"

rm -rf /tmp/pgtutor-drill
mkdir -p /tmp/pgtutor-drill

# 1. Siapkan "database korban" dengan data tetap.
psql -X -q -d postgres -c "DROP DATABASE IF EXISTS $DB_LATIHAN;" \
    -c "CREATE DATABASE $DB_LATIHAN;"
psql -X -q -d "$DB_LATIHAN" \
    -c "CREATE TABLE penjualan (id int PRIMARY KEY, item text, jumlah int);" \
    -c "INSERT INTO penjualan VALUES (1,'Kopi Torabika',12),(2,'Teh Melati',8),(3,'Gula Pasir',25);"

# 2. Checksum kondisi sebelum "bencana".
SEBELUM=$(psql -X -t -A -d "$DB_LATIHAN" -c "$PENGECEKAN")
echo "checksum sebelum : $SEBELUM"

# 3. Backup yang ingin kita uji (job harian versi chapter sebelumnya).
pg_dump -Fc -f "$BERKAS" "$DB_LATIHAN"

# 4. Bencana: database hilang total.
psql -X -q -d postgres -c "DROP DATABASE $DB_LATIHAN;" \
    -c "CREATE DATABASE $DB_LATIHAN;"

# 5. Pemulihan dari backup.
pg_restore -d "$DB_LATIHAN" "$BERKAS"

# 6. Checksum kondisi sesudah pemulihan.
SESUDAH=$(psql -X -t -A -d "$DB_LATIHAN" -c "$PENGECEKAN")
echo "checksum sesudah: $SESUDAH"

# 7. Putusan drill.
if [ "$SEBELUM" = "$SESUDAH" ]; then
    echo "HASIL DRILL: DATA IDENTIK"
else
    echo "HASIL DRILL: DATA BERBEDA" >&2
    exit 1
fi

# 8. Bersih-bersih.
psql -X -q -d postgres -c "DROP DATABASE $DB_LATIHAN;"
rm -rf /tmp/pgtutor-drill
