#!/bin/sh
# Run a Groovy script that uses picocli-groovy's @PicocliScript2.
set -eu

tmp=${AUTOPKGTEST_TMP:-$(mktemp -d)}
cd "$tmp"

CP=/usr/share/java/picocli.jar:/usr/share/java/picocli-groovy.jar

cat > greet.groovy <<'EOF'
@Command(name = "greet", mixinStandardHelpOptions = true, version = "greet 1.0",
         description = "Says hello from Groovy.")
@PicocliScript2
import groovy.transform.Field
import picocli.CommandLine.Command
import picocli.CommandLine.Option
import picocli.groovy.PicocliScript2

@Option(names = ["-n", "--name"], description = "Who to greet.")
@Field String name = "World"

@Option(names = "--count", description = "How many times.")
@Field int count = 1

assert this.commandLine.commandName == "greet"
count.times {
    println "Hello, ${name}!"
}
EOF

expect() {
    # expect <description> <pattern> <file>
    if grep -q -e "$2" "$3"; then
        echo "ok: $1"
    else
        echo "FAIL: $1: '$2' not found in:"
        cat "$3"
        exit 1
    fi
}

groovy -cp "$CP" greet.groovy > out.txt
expect "default value" '^Hello, World!$' out.txt

groovy -cp "$CP" greet.groovy --name Debian --count 2 > out.txt
[ "$(grep -c '^Hello, Debian!$' out.txt)" -eq 2 ] || { echo "FAIL: --count"; cat out.txt; exit 1; }
echo "ok: --name and --count"

groovy -cp "$CP" greet.groovy --help > out.txt
expect "--help shows description" 'Says hello from Groovy\.' out.txt
expect "--help lists --name" '--name=<name>' out.txt

groovy -cp "$CP" greet.groovy --version > out.txt
expect "--version" '^greet 1\.0$' out.txt

# PicocliBaseScript2 reports the error and returns the exit code as the
# script result instead of exiting, so the groovy launcher still exits 0.
groovy -cp "$CP" greet.groovy --bogus > out.txt 2> err.txt || true
expect "unknown option message" "Unknown option: '--bogus'" err.txt
if grep -q Hello out.txt; then
    echo "FAIL: script body ran despite the unknown option"
    cat out.txt
    exit 1
fi
echo "ok: script body did not run"
