#!/bin/sh
set -eu
umask 077

ROOT=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"

if [ ! -f "$ROOT/.env" ]; then
  echo "Missing $ROOT/.env." >&2
  exit 1
fi

set -a
# shellcheck source=/dev/null
. "$ROOT/.env"
set +a

if [ "${DATABASE_MODE:-container}" != container ]; then
  echo "backup-compose.sh only operates on DATABASE_MODE=container." >&2
  echo "Use the external PostgreSQL provider's verified backup workflow instead." >&2
  exit 1
fi

: "${POSTGRES_DB:?Set POSTGRES_DB in .env}"
: "${POSTGRES_USER:?Set POSTGRES_USER in .env}"

timestamp=$(date -u +%Y%m%d-%H%M%S)
target=${1:-"$ROOT/output/backups/compose-$timestamp.dump"}
target_dir=$(dirname -- "$target")
target_name=$(basename -- "$target")
partial="$target.partial.$$"
checksum="$target.sha256"
checksum_partial="$checksum.partial.$$"

if [ -e "$target" ] || [ -e "$checksum" ]; then
  echo "Refusing to overwrite $target or $checksum." >&2
  exit 1
fi

mkdir -p "$target_dir"

cleanup() {
  rm -f "$partial" "$checksum_partial"
}
trap cleanup EXIT HUP INT TERM

"$ROOT/scripts/compose.sh" "$ROOT/.env" exec -T db \
  pg_dump \
  --username "$POSTGRES_USER" \
  --dbname "$POSTGRES_DB" \
  --format custom \
  --no-owner >"$partial"

test -s "$partial"

"$ROOT/scripts/compose.sh" "$ROOT/.env" exec -T db pg_restore --list <"$partial" >/dev/null

hash=$(sha256sum "$partial" | awk '{print $1}')
printf '%s  %s\n' "$hash" "$target_name" >"$checksum_partial"

mv "$partial" "$target"
mv "$checksum_partial" "$checksum"
trap - EXIT HUP INT TERM

echo "Backup: $target"
echo "Checksum: $checksum"
echo "SHA-256: $hash"
