#!/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.
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=$(su -s /bin/sh postgres -c "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)..."
    su -s /bin/sh postgres -c "psql -c 'CREATE ROLE argus LOGIN;'"
fi

db_exists=$(su -s /bin/sh postgres -c "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)..."
    su -s /bin/sh postgres -c "createdb -O argus argus"
fi

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