#!/bin/bash
set -e -o pipefail
exec 2>&1

# shellcheck disable=SC2154
trap '
  exitcode=$?
  { set +x; } &> /dev/null
  if [[ "$exitcode" != 0 ]]; then
    echo
    echo "FAILED!"
    exit 1
  fi
' EXIT

cd "$(dirname "${BASH_SOURCE[0]}")"
export PGHOST=127.0.0.1
export PGPORT=55432
export PGUSER=postgres
export PGPASSWORD=postgres

if [[ "$DROPDB" != 0 ]]; then
  dbs=$(psql -t -c "SELECT datname FROM pg_database WHERE starts_with(datname, 'ci_')")
  for db in $dbs; do
    psql -c "DROP DATABASE \"$db\" WITH (FORCE)" >/dev/null
  done
fi

prefix_tee() (
  { set +x; } &> /dev/null
  prefix="$1"
  shift
  sed -u "s/^/[$prefix] /" | tee "$@"
)

run_py_code() (
  { set +x; } &> /dev/null
  python -c "$(echo "
    __import__('sys').dont_write_bytecode = True
    from importlib.machinery import SourceFileLoader
    from importlib.util import spec_from_loader, module_from_spec
    spec = spec_from_loader('module', SourceFileLoader('module', '../ci-pg-restore'))
    module = module_from_spec(spec)
    spec.loader.exec_module(module)
    globals().update(module.__dict__)
    $1
  " | sed -E 's/^ +//g')"
)

export error=0

set -o xtrace
