#!/usr/bin/env bash
# Fake psql: state under $FAKE/pg (pw, attrs, members) for the one role whp_panel.
set -euo pipefail
printf '%s\n' "$*" >> "$FAKE/argv"
user=""; c=""
while [ $# -gt 0 ]; do case "$1" in -U) user="$2"; shift ;; -c) c="$2"; shift ;; esac; shift; done
mkdir -p "$FAKE/pg"
if [ "$user" != postgres ]; then
    [ -f "$FAKE/pg/pw" ] || exit 2
    want="$(cat "$FAKE/pg/pw")"; got="$(cut -d: -f5 "$PGPASSFILE")"
    [ "$want" = "$got" ] || exit 2
    exit 0
fi
[ "$PGPASSFILE" = "$FAKE_ROOT_PGPASS" ] || { echo "postgres login without the root passfile" >&2; exit 2; }
while IFS= read -r line; do
    [ -n "$line" ] || continue
    echo "$line" | sed -E "s/PASSWORD '[^']*'/PASSWORD '<pw>'/" >> "$FAKE/pglog"
    # Real PostgreSQL has no integer || integer operator (measured on PG16):
    # refuse it the way the server does, so a script that relies on it fails here.
    case "$line" in *"::int||"*) echo "ERROR:  operator does not exist: integer || integer" >&2; exit 1 ;; esac
    case "$line" in
        "SELECT 1 FROM pg_roles WHERE rolname = 'whp_panel';") [ -f "$FAKE/pg/pw" ] && echo 1; true ;;
        "CREATE ROLE whp_panel LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS PASSWORD '"*)
            p="${line##*PASSWORD \'}"; echo "${p%\';}" > "$FAKE/pg/pw"; echo 000001 > "$FAKE/pg/attrs"; : > "$FAKE/pg/members" ;;
        "ALTER ROLE whp_panel LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;")
            [ -f "$FAKE/pg/attrs_stuck" ] || echo 000001 > "$FAKE/pg/attrs" ;;
        "GRANT pg_read_all_stats TO whp_panel;") grep -qx pg_read_all_stats "$FAKE/pg/members" || echo pg_read_all_stats >> "$FAKE/pg/members" ;;
        "ALTER ROLE whp_panel PASSWORD '"*) p="${line##*PASSWORD \'}"; echo "${p%\';}" > "$FAKE/pg/pw" ;;
        "REVOKE CONNECT ON DATABASE template1 FROM PUBLIC;") : ;;
        "SELECT pg_catalog.format('REVOKE CONNECT"*) [ ! -f "$FAKE/pg/t1grants" ] || cat "$FAKE/pg/t1grants" ;;
        "REVOKE CONNECT ON DATABASE template1 FROM \""*) : > "$FAKE/pg/t1grants" ;;
        "SELECT DISTINCT r.rolname FROM pg_catalog.pg_shdepend"*) [ ! -f "$FAKE/pg/t1polluted" ] || cat "$FAKE/pg/t1polluted" ;;
        "DROP OWNED BY "*) : > "$FAKE/pg/t1polluted" ;;
        "SELECT rolsuper::int::text"*) cat "$FAKE/pg/attrs" ;;
        "SELECT r.rolname FROM pg_auth_members"*) sort "$FAKE/pg/members" ;;
        *) echo "fake psql: unknown statement: $line" >&2; exit 3 ;;
    esac
done
