#!/usr/bin/env bash
# psql for 04-migrate.sh on a machine without one: runs psql 15 inside the
# database container. The URL keeps its user and password but connects to
# the container's own network name, not 127.0.0.1 -- inside the container
# loopback is trusted without a password, supabase-db is not, so password
# and role are checked as on the server.
#
# `-f FILE` and `-f -` (stdin) are copied into the container and read there
# with `-f <copy>`: Docker Desktop's `docker exec -i` stdin forwarding stalled
# mid-file on Windows (R14: 0046_contracts.sql sat "idle in transaction" for
# minutes, psql waiting for the rest of its input). Error messages then name
# the copy (psql:/tmp/psql-in-*.sql:<line>) instead of <stdin>.
set -euo pipefail
ctr="${R3_DB_CONTAINER:-${STACK_NAME:-r3}-supabase-db-1}"
remote="/tmp/psql-in-$$-${RANDOM}.sql"
args=() file="" feed=0
while [ $# -gt 0 ]; do
  case "$1" in
    postgres://*|postgresql://*)
      url="$1"
      user="$(printf '%s' "$url" | sed -E 's#^postgres(ql)?://([^:@/]+).*#\2#')"
      pw="$(printf '%s' "$url" | sed -E 's#^postgres(ql)?://[^:]+:([^@]*)@.*#\2#')"
      export PGPASSWORD="$pw"
      args+=("postgres://${user}@supabase-db:5432/postgres")
      ;;
    -f)
      feed=1
      [ "$2" = "-" ] || file="$2"
      # in place: psql runs -f and -c in the order given
      args+=(-f "$remote")
      shift ;;
    *) args+=("$1") ;;
  esac
  shift
done
if [ "$feed" = "0" ]; then
  exec env MSYS_NO_PATHCONV=1 docker exec -i -e PGPASSWORD "$ctr" psql "${args[@]}"
fi
local_copy="$(mktemp)"
trap 'rm -f "$local_copy"; MSYS_NO_PATHCONV=1 docker exec "$ctr" rm -f "$remote" >/dev/null 2>&1 || true' EXIT
if [ -n "$file" ]; then cat "$file" > "$local_copy"; else cat > "$local_copy"; fi
chmod 644 "$local_copy"
# docker.exe needs a Windows path for the source (Git Bash's /tmp is not one).
src="$(cygpath -w "$local_copy" 2>/dev/null || printf '%s' "$local_copy")"
MSYS_NO_PATHCONV=1 docker cp -q "$src" "$ctr:$remote"
MSYS_NO_PATHCONV=1 docker exec -e PGPASSWORD "$ctr" psql "${args[@]}"
