#!/bin/bash
# ovedr-pg-setup — the class's PostgreSQL server on a CentOS Stream 10 VM (Demo 1a, "build it yourself").
# GENERATED by automation/tools/pg_setup_script.sh from workload/sql/*.sql: the same schema and toolkit as the class
# Template and the Windows VMs.
#
# Your cloud-init runs it once, as root, after writing /root/.ovedr-db (root-only) with two lines:
#   DB_USER=student_01
#   DB_PASSWORD=<your class password>
# It installs PostgreSQL 16, opens it to the lab network (10.0.0.0/8, password logins), creates the class database
# `bcdr` with its toolkit (marks, ovedr_mark, ovedr_verify, heartbeat), your database login, and the heartbeat service,
# then deletes /root/.ovedr-db. The last line it prints is OVEDR-READY.
set -euo pipefail
[ "$(id -u)" = 0 ] || { echo "run as root (cloud-init runcmd does)" >&2; exit 1; }
[ -r /root/.ovedr-db ] || { echo "no /root/.ovedr-db: write DB_USER and DB_PASSWORD there first" >&2; exit 1; }
DB_USER="$(sed -n 's/^DB_USER=//p' /root/.ovedr-db | head -n1)"
DB_PASSWORD="$(sed -n 's/^DB_PASSWORD=//p' /root/.ovedr-db | head -n1)"
[ -n "$DB_USER" ] && [ -n "$DB_PASSWORD" ] || { echo "/root/.ovedr-db needs DB_USER= and DB_PASSWORD=" >&2; exit 1; }
SQL=/usr/local/share/ovedr; mkdir -p "$SQL"

dnf -y -q install postgresql-server qemu-guest-agent
if [ ! -s /var/lib/pgsql/data/PG_VERSION ]; then
  # Data and WAL disks, if the student's cloud-init mounted them (twisty, step 4): PostgreSQL owns them and the WAL goes on
  # its own disk, as in the class Template. Without them, everything stays on the system disk.
  W=
  for d in data wal; do
    if mountpoint -q /var/lib/pgsql/$d; then chown postgres:postgres /var/lib/pgsql/$d; chmod 700 /var/lib/pgsql/$d; fi
  done
  if mountpoint -q /var/lib/pgsql/wal; then W="--waldir=/var/lib/pgsql/wal/pg_wal"; fi
  PGSETUP_INITDB_OPTIONS="$W --auth-local=peer --auth-host=scram-sha-256" postgresql-setup --initdb
  echo "listen_addresses = '*'" >> /var/lib/pgsql/data/postgresql.conf
  echo "host all all 10.0.0.0/8 scram-sha-256" >> /var/lib/pgsql/data/pg_hba.conf
fi
systemctl enable --now postgresql qemu-guest-agent
# an online VM snapshot freezes every filesystem through the guest agent; SELinux lets it reach /var/lib/pgsql only with this
setsebool -P virt_qemu_ga_read_nonsecurity_files on

# the class database: the same schema and toolkit the Windows VMs run
cat > "$SQL/schema.sql" <<'OVEDR_SQL'
-- BCDR heartbeat schema. Run once as the postgres superuser:
--   psql -U postgres -f schema.sql
-- Database `bcdr`, owner `bcdr`. The writer inserts every 5 s; students insert named rows.

CREATE ROLE bcdr LOGIN;                       -- password set by Install-Heartbeat.ps1
CREATE DATABASE bcdr OWNER bcdr;
\connect bcdr

CREATE TABLE heartbeat (
    id      bigserial   PRIMARY KEY,
    ts      timestamptz NOT NULL DEFAULT clock_timestamp(),   -- wall clock at insert, not txn start
    writer  text        NOT NULL,                             -- 'auto' or a student account
    note    text
);
CREATE INDEX heartbeat_ts ON heartbeat (ts);
ALTER TABLE heartbeat OWNER TO bcdr;

-- Every move the class makes, for the proof table.
CREATE TABLE move_log (
    id          bigserial   PRIMARY KEY,
    ts          timestamptz NOT NULL DEFAULT clock_timestamp(),
    step        text        NOT NULL,        -- e.g. 'm4-before', 'm4-after'
    max_hb_id   bigint,
    pg_started  timestamptz NOT NULL DEFAULT pg_postmaster_start_time()
);
ALTER TABLE move_log OWNER TO bcdr;
OVEDR_SQL
cat > "$SQL/integrity.sql" <<'OVEDR_SQL'
-- Data-integrity toolkit: what every student runs at every stage of every demo.
-- Idempotent: Setup-SourceVm.ps1 applies it on each converge, as the postgres superuser:
--   psql -U postgres -d bcdr -f integrity.sql
--
--   SELECT * FROM ovedr_mark('student-03', 'd1-before-migration');   -- inject: one named, hash-chained row
--   SELECT * FROM ovedr_load('student-03', 'd2-load', 500);          -- inject: a burst of rows (a busy database)
--   SELECT * FROM ovedr_verify('student-03');                        -- read: are all my rows here, chain intact?
--   SELECT * FROM ovedr_checksum();                                  -- read: one fingerprint of every mark
--
-- Each row's sha = sha256(previous row's sha for that student ‖ student ‖ stage ‖ payload ‖ ts in UTC, µs). A row
-- that is lost, altered or reordered breaks that student's chain, and ovedr_verify says where.
\connect bcdr

CREATE TABLE IF NOT EXISTS marks (
    id       bigserial   PRIMARY KEY,
    ts       timestamptz NOT NULL DEFAULT clock_timestamp(),
    student  text        NOT NULL,
    stage    text        NOT NULL,
    payload  text        NOT NULL DEFAULT '',
    prev_sha text        NOT NULL,
    sha      text        NOT NULL
);
CREATE INDEX IF NOT EXISTS marks_student ON marks (student, id);
ALTER TABLE marks OWNER TO bcdr;

CREATE OR REPLACE FUNCTION ovedr_mark(p_student text, p_stage text, p_payload text DEFAULT '')
RETURNS TABLE (id bigint, ts timestamptz, stage text, sha text) LANGUAGE plpgsql AS $$
DECLARE prev text; t timestamptz := clock_timestamp();
BEGIN
  PERFORM pg_advisory_xact_lock(hashtext(p_student));          -- one chain per student, no races
  SELECT m.sha INTO prev FROM marks m WHERE m.student = p_student ORDER BY m.id DESC LIMIT 1;
  prev := coalesce(prev, 'genesis');
  RETURN QUERY
  INSERT INTO marks AS m (ts, student, stage, payload, prev_sha, sha)
  VALUES (t, p_student, p_stage, p_payload, prev,
          encode(sha256(convert_to(prev || '|' || p_student || '|' || p_stage || '|' || p_payload || '|' || to_char(t AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US'), 'UTF8')), 'hex'))
  RETURNING m.id, m.ts, m.stage, left(m.sha, 12);
END $$;
ALTER FUNCTION ovedr_mark(text, text, text) OWNER TO bcdr;

CREATE OR REPLACE FUNCTION ovedr_load(p_student text, p_stage text, p_rows int DEFAULT 100)
RETURNS TABLE (rows_written int, first_id bigint, last_id bigint, seconds numeric) LANGUAGE plpgsql AS $$
DECLARE a bigint; b bigint; t0 timestamptz := clock_timestamp();
BEGIN
  FOR i IN 1..p_rows LOOP
    SELECT o.id INTO b FROM ovedr_mark(p_student, p_stage, 'load ' || i || '/' || p_rows || ' ' || md5(random()::text)) o;
    IF i = 1 THEN a := b; END IF;
  END LOOP;
  RETURN QUERY SELECT p_rows, a, b, round(extract(epoch FROM clock_timestamp() - t0)::numeric, 2);
END $$;
ALTER FUNCTION ovedr_load(text, text, int) OWNER TO bcdr;

CREATE OR REPLACE FUNCTION ovedr_verify(p_student text DEFAULT NULL)
RETURNS TABLE (student text, marks bigint, last_stage text, last_ts timestamptz, chain_ok boolean, first_break bigint)
LANGUAGE sql STABLE AS $$
  WITH c AS (
    SELECT m.*, lag(m.sha) OVER (PARTITION BY m.student ORDER BY m.id) AS want_prev,
           encode(sha256(convert_to(m.prev_sha || '|' || m.student || '|' || m.stage || '|' || m.payload || '|' || to_char(m.ts AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US'), 'UTF8')), 'hex') AS want_sha
    FROM marks m WHERE p_student IS NULL OR m.student = p_student)
  SELECT c.student, count(*),
         (array_agg(c.stage ORDER BY c.id DESC))[1], max(c.ts),
         bool_and(c.sha = c.want_sha AND c.prev_sha = coalesce(c.want_prev, 'genesis')),
         min(c.id) FILTER (WHERE NOT (c.sha = c.want_sha AND c.prev_sha = coalesce(c.want_prev, 'genesis')))
  FROM c GROUP BY c.student ORDER BY c.student
$$;
ALTER FUNCTION ovedr_verify(text) OWNER TO bcdr;

CREATE OR REPLACE FUNCTION ovedr_checksum()
RETURNS TABLE (marks bigint, last_id bigint, fingerprint text) LANGUAGE sql STABLE AS $$
  SELECT count(*), max(id), left(md5(string_agg(sha, '' ORDER BY id)), 16) FROM marks
$$;
ALTER FUNCTION ovedr_checksum() OWNER TO bcdr;
OVEDR_SQL
cat > "$SQL/class.sql" <<'OVEDR_SQL'
-- the class role, the guest-tools report, and what a student may do (as on the Windows VMs)
CREATE ROLE ovedr_class NOLOGIN;
GRANT CONNECT ON DATABASE bcdr TO ovedr_class;
\connect bcdr
CREATE TABLE IF NOT EXISTS guest_tools (id bigserial PRIMARY KEY, ts timestamptz NOT NULL DEFAULT clock_timestamp(),
                                        platform text, vmtools text, qemu_ga text, virtio text);
ALTER TABLE guest_tools OWNER TO bcdr;
GRANT USAGE ON SCHEMA public TO ovedr_class;
GRANT SELECT, INSERT ON marks, heartbeat TO ovedr_class;
GRANT SELECT ON move_log, guest_tools TO ovedr_class;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO ovedr_class;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO ovedr_class;
-- your own login (psql quotes both values)
CREATE ROLE :"usr" LOGIN PASSWORD :'pw' IN ROLE ovedr_class;
OVEDR_SQL
if ! runuser -u postgres -- psql -XAtc "SELECT 1 FROM pg_database WHERE datname = 'bcdr'" | grep -q 1; then
  runuser -u postgres -- psql -X -q -v ON_ERROR_STOP=1 -f "$SQL/schema.sql"
  runuser -u postgres -- psql -X -q -v ON_ERROR_STOP=1 -d bcdr -f "$SQL/integrity.sql"
  runuser -u postgres -- psql -X -q -v ON_ERROR_STOP=1 -v usr="$DB_USER" -v pw="$DB_PASSWORD" -f "$SQL/class.sql"
fi
shred -u /root/.ovedr-db

# the heartbeat: one row every 5 s (gaps are outages), and a guest-tools report at start
cat > /usr/local/sbin/ovedr-heartbeat <<'OVEDR_SH'
#!/bin/bash
psql -X -q -d bcdr -c "INSERT INTO guest_tools (platform, vmtools, qemu_ga, virtio) VALUES
  ('$(systemd-detect-virt)', 'absent', '$(systemctl is-active qemu-guest-agent)',
   '$(lsmod | awk '/^virtio/ {print $1}' | sort | paste -sd, -)')"
while :; do
  psql -X -q -d bcdr -c "INSERT INTO heartbeat (writer, note) VALUES ('auto', 'centos10')" || true
  sleep 5
done
OVEDR_SH
chmod 0755 /usr/local/sbin/ovedr-heartbeat
cat > /etc/systemd/system/ovedr-heartbeat.service <<'OVEDR_UNIT'
[Unit]
Description=ovedr heartbeat: a row in bcdr.heartbeat every 5 seconds
After=postgresql.service
Requires=postgresql.service
[Service]
User=postgres
ExecStart=/usr/local/sbin/ovedr-heartbeat
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
OVEDR_UNIT
systemctl daemon-reload
systemctl enable --now ovedr-heartbeat
echo "OVEDR-READY $(hostname) postgresql $(runuser -u postgres -- psql -XAtc 'SHOW server_version')"
