#!/bin/sh
# PREPARE_HOOK: SOURCE is an existing private staging parent, not PGDATA.
set -eu
[ "$#" = 2 ] || exit 2
: "${PGDATABASE:?configure PGDATABASE como nome do banco}"
case "$PGDATABASE" in *'='*|postgres://*|postgresql://*) echo 'use nome simples em PGDATABASE; autenticação via libpq/PGPASSFILE' >&2; exit 2 ;; esac
case "${PG_GLOBALS:-0}" in 0|1) ;; *) echo 'PG_GLOBALS deve ser 0 ou 1' >&2; exit 2 ;; esac
case "$1" in /*) ;; *) echo 'SOURCE deve ser diretório absoluto de staging' >&2; exit 2 ;; esac
parent=$(realpath -e -- "$1")
[ -d "$parent" ] && [ "$(stat -c %u -- "$parent")" = "$(id -u)" ] &&
    [ "$(stat -c %a -- "$parent")" = 700 ] || { echo 'staging deve pertencer ao usuário e ter modo 0700' >&2; exit 2; }
tool() {
    program=$1; shift
    if [ -n "${PG_BIN_DIR:-}" ]; then "$PG_BIN_DIR/$program" "$@"; else "$program" "$@"; fi
}
if [ -n "${PG_STORAGE_TYPE:-}${PG_STORAGE_ID:-}${PG_STORAGE_MOUNT:-}" ]; then
    "${SCHIPSAVE_PROTECTED_BIN:-/usr/bin/schipsave-protected}" \
        "${PG_STORAGE_TYPE:?}" "${PG_STORAGE_ID:?}" "${PG_STORAGE_MOUNT:?}" -- --check "$parent"
fi
umask 077
stage=$(mktemp -d "$parent/.postgresql-XXXXXXXX")
cleanup() { result=$?; trap - EXIT; if [ "$result" != 0 ]; then rm -rf -- "$stage"; fi; exit "$result"; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
printf '1\n' > "$stage/.schipsave-postgresql"
# Let schipsave compress chunks; avoid spending CPU on nested dump compression.
tool pg_dump --no-password --format=custom --compress=0 --file="$stage/database.dump"
tool pg_restore --list "$stage/database.dump" > /dev/null
if [ "${PG_GLOBALS:-0}" = 1 ]; then
    tool pg_dumpall --no-password --globals-only -l "$PGDATABASE" --file="$stage/globals.sql"
fi
tool pg_dump --version > "$stage/client-version.txt"
printf '%s\n' "$stage"
