#!/bin/sh
# Check the command line interface: help, version and argument validation.
# No network access is needed.
set -eu

cd "${AUTOPKGTEST_TMP:-$(mktemp -d)}"
export HOME="$PWD"

fail() { echo "FAIL: $*" >&2; exit 1; }

# run <expected exit code> <args...>: output goes to ./out
run() {
    expected=$1; shift
    rc=0
    evil-winrm "$@" </dev/null >out 2>&1 || rc=$?
    if [ "$rc" -ne "$expected" ]; then
        cat out
        fail "evil-winrm $* exited with $rc, expected $expected"
    fi
    if grep -Eq '\.rb:[0-9]+:in ' out; then
        cat out
        fail "evil-winrm $* printed a Ruby backtrace"
    fi
}

expect() {
    grep -qF -- "$1" out || { cat out; fail "missing in output: $1"; }
}

echo "Test: --help"
run 0 --help
expect "Usage: evil-winrm -i IP -u USER"
for opt in --ssl --ip --user --password --hash --port --realm --ccache --version; do
    expect "$opt"
done

echo "Test: --version matches the package version"
pkgver=$(dpkg-query -W -f '${Version}' evil-winrm | sed -e 's/^[0-9]*://' -e 's/-[^-]*$//')
run 0 --version
[ "$(cat out)" = "v$pkgver" ] || fail "version is '$(cat out)', expected 'v$pkgver'"

echo "Test: missing mandatory arguments"
run 1 -n
expect "missing argument: ip, user"

echo "Test: invalid option"
run 1 -n --does-not-exist
expect "invalid option: --does-not-exist"

echo "Test: invalid NT hash"
run 1 -n -i 127.0.0.1 -u user -H not-a-hash
expect "Invalid hash format"

echo "Test: password and hash are mutually exclusive"
run 1 -n -i 127.0.0.1 -u user -p pass -H 31d6cfe0d16ae931b73c59d7e0c089c0
expect "Both at the same time are not allowed"

echo "Test: non-existent scripts directory"
run 1 -n -i 127.0.0.1 -u user -p pass -s "$PWD/missing"
expect "used for scripts was not found"

echo "Test: non-existent executables directory"
run 1 -n -i 127.0.0.1 -u user -p pass -e "$PWD/missing"
expect "used for executables was not found"

echo "Test: missing SSL certificate files"
run 1 -n -i 127.0.0.1 -u user -S -c "$PWD/missing.crt" -k "$PWD/missing.key"
expect "can't be found"

echo "All CLI tests passed"
