#!/usr/bin/env bash

# Testing the upgrade subcommand on PuppetDB jar
# Migrates an empty database to most recent migration.
# You can specify PuppetDB jar location with env var PDB_JAR.
# PuppetDB configuration is sourced from PDBBOX sandbox or an ephemeral sandbox
# Flags --pgbin and --pgbin are necessary unless set with ext/bin/test-config

set -euo pipefail

usage() { echo 'Usage: [PDB_JAR=JAR] $(basename "$0") --pgbin PGBIN --pgport PGPORT'; }
misuse() { usage 1>&2; exit 2; }

argv=("$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" "$@")
declare -A opt

# Validate arguments
while test $# -gt 0; do
    case "$1" in
        --pgbin|--pgport)
            test $# -gt 1 || misuse
            opt["${1:2}"]="$2"
            shift 2
            ;;
        *)
            misuse
    esac
done

# Ensure we have pgbin value
if test -z "${opt[pgbin]:-}"; then
    opt[pgbin]="$(ext/bin/test-config --get pgbin)"
    if test  -z "${opt[pgbin]:-}"; then
        echo 'Please specify --pgbin or set pgbin with ext/bin/test-config' 1>&2
        exit 2
    fi
fi

# Ensure we have pgport value
if test -z "${opt[pgport]:-}"; then
    opt[pgport]="$(ext/bin/test-config --get pgport)"
     if test  -z "${opt[pgport]:-}"; then
        echo 'Please specify --pgport or set pgport with ext/bin/test-config' 1>&2
        exit 2
    fi
fi

set -x

# Ensure there is a PuppetDB sandbox available
if test -z "${PDBBOX:-}"; then
    # No PDBBOX, set one up and run ourselves again
    tmpdir="$(mktemp -d "test-upgrade-and-exit-XXXXXX")"
    tmpdir="$(cd "$tmpdir" && pwd)"
    trap "$(printf 'rm -rf %q' "$tmpdir")" EXIT
    # Don't exec (or we'll never run the trap)
    ext/bin/with-pdbbox --box "$tmpdir/box" \
                        --pgbin "${opt[pgbin]}" --pgport "${opt[pgport]}" \
                        -- "${argv[@]}"
    exit 0
fi

# Create temporary directory for storing output
tmpdir="$(mktemp -d "test-upgrade-and-exit-XXXXXX")"
tmpdir="$(cd "$tmpdir" && pwd)"
trap "$(printf 'rm -rf %q' "$tmpdir")" EXIT

test ! -e "$PDBBOX"/var/mq-migrated

# Ensure database "puppetdb" has no tables
psql -U puppetdb puppetdb -c '\dt' >"$tmpdir/out" 2>"$tmpdir/err"
cat "$tmpdir/out"
cat "$tmpdir/err"
# Output moved to err and changed as of at least pg 11
grep 'No relations found' "$tmpdir/out" \
    || grep 'Did not find any relations' "$tmpdir/err"

# Run upgrade
./pdb upgrade -c "$PDBBOX/conf.d"

# Ensure maximum migration id matches most recent migration id
psql -U puppetdb puppetdb -c 'select max(version) from schema_migrations;' \
     > "$tmpdir/out"
cat "$tmpdir/out"
# This must be updated every time we add a new migration
grep -qE ' 88$' "$tmpdir/out"

test ! -e "$PDBBOX"/var/mq-migrated
