#!/usr/bin/env bash

# Runs simple tests on PuppetDB jar command line ouptput.
# PuppetDB is started without configuration
# PostgreSQL is not necessary

set -uexo pipefail

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

test $# -eq 0 || misuse

jdkver=$(ext/bin/jdk-info --print major)

# Number of characters expected for stderr output for subcommands
expected_help_warnings=0
expected_version_warnings=0
case "$jdkver" in
    8)
      # Java 8 deprecation warning
      expected_help_warnings=60
      expected_version_warnings=60
        ;;
    11 | 17)
        ;;
    *)
        echo "JDK version '$jdkver' is not supported" 1>&2
        exit 3
        ;;
esac

# Create temporary directory to store output
tmpdir="$(mktemp -d "test-top-level-cli-XXXXXX")"
tmpdir="$(cd "$tmpdir" && pwd)"
trap "$(printf 'rm -rf %q' "$tmpdir")" EXIT

# Test if unknown command produces correct output and exit status
rc=0
./pdb frobnicate ... 1>"$tmpdir/out" 2>"$tmpdir/err" || rc=$?
cat "$tmpdir/out" "$tmpdir/err"
test "$rc" -eq 2
grep -F 'Available subcommands:' "$tmpdir/err"
grep -E 'Display version information' "$tmpdir/err"

# Test if help subcommand produces correct outout
rc=0
./pdb help 1>"$tmpdir/out" 2>"$tmpdir/err" || rc=$?
cat "$tmpdir/out" "$tmpdir/err"
test "$rc" -eq 0
grep -F 'Available subcommands:' "$tmpdir/out"
grep -F 'Display version information' "$tmpdir/out"

# Test if number of characters from stderr output matches what is expected
if ! test $(wc -c < "$tmpdir/err") -eq "$expected_help_warnings"; then
    echo 'ERROR: Unpected help warnings:' 1>&2
    cat "$tmpdir/err"
    false
fi

# Test if version subcommand produces correct output
rc=0
./pdb version 1>"$tmpdir/out" 2>"$tmpdir/err" || rc=$?
cat "$tmpdir/out" "$tmpdir/err"
test "$rc" -eq 0
grep -E '^version=' "$tmpdir/out"
grep -E '^target_schema_version=' "$tmpdir/out"
test $(wc -c < "$tmpdir/err") -eq $expected_version_warnings
