#!/usr/bin/env bash
# Mengukur durasi komponen drill -- angka waktu bervariasi antar mesin
# dan antar eksekusi; yang stabil hanya orde besarannya.
set -euo pipefail

DB_LATIHAN=probe_drill_waktu
BERKAS=/tmp/pgtutor-drill/waktu.dump
PGBIN=/home/z/my-project/tools/dl/pgdeb/usr/lib/postgresql/17/bin

bersihkan() {
    "$PGBIN/pg_ctl" -D /tmp/pgtutor-drill/fisik-waktu stop >/dev/null 2>&1 || true
    psql -X -q -d postgres -c "DROP DATABASE IF EXISTS $DB_LATIHAN;" >/dev/null 2>&1 || true
    rm -rf /tmp/pgtutor-drill
}
trap bersihkan EXIT

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

# Siapkan database korban (sama dengan drill logis).
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);"
pg_dump -Fc -f "$BERKAS" "$DB_LATIHAN"

echo "== restore logis (drop + create + pg_restore):"
psql -X -q -d postgres -c "DROP DATABASE $DB_LATIHAN;" -c "CREATE DATABASE $DB_LATIHAN;"
time pg_restore -d "$DB_LATIHAN" "$BERKAS"

echo "== base backup + start instance baru:"
time pg_basebackup -D /tmp/pgtutor-drill/fisik-waktu -Fp -Xs --checkpoint=fast --no-password
time "$PGBIN/pg_ctl" -D /tmp/pgtutor-drill/fisik-waktu \
    -l /tmp/pgtutor-drill/waktu.log \
    -o "-p 54330 -k /tmp -c listen_addresses=''" start >/dev/null 2>&1
"$PGBIN/pg_ctl" -D /tmp/pgtutor-drill/fisik-waktu stop >/dev/null 2>&1
