#!/bin/sh
# ADR-0040 M7: idempotent native PostgreSQL role+database provisioning for
# argus-api's peer-authenticated unix-socket connection (no password --
# confirmed live that Debian's default pg_hba.conf already grants
# `local all all peer`, no config needed). Safe to re-run at any time.
#
# Uses `runuser`, not `su`, to drop to the postgres user. Found live
# (2026-09-03, re-verifying this milestone against current HEAD in a real
# systemd-PID-1 container): `su` failed unconditionally here with
# "Authentication failure" even when invoked as root, journald showing
# `pam_unix(su:account): read unix_chkpwd output error 0: Success` --
# the setuid `unix_chkpwd` helper `su`'s PAM stack shells out to did not
# behave correctly in that sandboxed environment. `runuser` performs the
# identical privilege drop for a root-invoked administrative script
# without going through `unix_chkpwd`/the `su`-specific PAM account stack
# at all, and was confirmed working in the same environment where `su`
# failed. Whether that `su` failure would also occur on real appliance
# hardware wasn't established either way -- `runuser` is the more robust
# choice regardless, so switching costs nothing and removes the dependency
# on a setuid helper behaving correctly.
set -e

if ! command -v psql >/dev/null 2>&1 || ! pg_isready -q 2>/dev/null; then
    echo "[argus-db-provision] PostgreSQL not installed/reachable yet -- skipping." >&2
    echo "[argus-db-provision] Re-run 'argus-db-provision' (as root) once postgresql-17 is installed and running." >&2
    exit 0
fi

role_exists=$(runuser -u postgres -- psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='argus'" 2>/dev/null || true)
if [ "$role_exists" != "1" ]; then
    echo "[argus-db-provision] Creating role 'argus' (peer auth, no password)..."
    runuser -u postgres -- psql -c 'CREATE ROLE argus LOGIN;'
fi

db_exists=$(runuser -u postgres -- psql -tAc "SELECT 1 FROM pg_database WHERE datname='argus'" 2>/dev/null || true)
if [ "$db_exists" != "1" ]; then
    echo "[argus-db-provision] Creating database 'argus' (owner: argus)..."
    runuser -u postgres -- createdb -O argus argus
fi

echo "[argus-db-provision] Done -- 'argus' role and database ready for peer-authenticated connections."
