#!/bin/sh
# Check that every jar shipped in libpicocli-java is present, is reachable
# through /usr/share/java and the Maven repository, and contains the
# classes of the module it is named after.
set -eu

version=$(dpkg-query -W -f '${Version}' libpicocli-java | sed -e 's/^[0-9]*://' -e 's/-[^-]*$//')
status=0

fail() {
    echo "FAIL: $*"
    status=1
}

check() {
    module=$1
    class=$2
    for jar in \
        /usr/share/java/$module.jar \
        /usr/share/java/$module-$version.jar \
        /usr/share/maven-repo/info/picocli/$module/$version/$module-$version.jar \
        /usr/share/maven-repo/info/picocli/$module/debian/$module-debian.jar
    do
        if [ ! -r "$jar" ]; then
            fail "$jar is missing or dangling"
            continue
        fi
        if ! unzip -l "$jar" | grep -q " $class\$"; then
            fail "$jar does not contain $class"
            continue
        fi
        echo "ok: $jar contains $class"
    done
    for pom in \
        /usr/share/maven-repo/info/picocli/$module/$version/$module-$version.pom \
        /usr/share/maven-repo/info/picocli/$module/debian/$module-debian.pom
    do
        if grep -q "<artifactId>$module</artifactId>" "$pom"; then
            echo "ok: $pom"
        else
            fail "$pom is missing or does not describe $module"
        fi
    done
}

check picocli picocli/CommandLine.class
check picocli-codegen picocli/codegen/docgen/manpage/ManPageGenerator.class
check picocli-shell-jline2 picocli/shell/jline2/PicocliJLineCompleter.class
check picocli-shell-jline3 picocli/shell/jline3/PicocliCommands.class
check picocli-groovy picocli/groovy/PicocliScript2.class

# Each module jar must contain only its own classes (picocli-codegen used to
# be a copy of the picocli-shell-jline2 jar).
for module in codegen shell/jline2 shell/jline3 groovy; do
    jar=/usr/share/java/picocli-$(echo $module | tr / -).jar
    others=$(unzip -Z1 "$jar" | grep '^picocli/.*\.class$' | grep -v "^picocli/$module/" || true)
    if [ -n "$others" ]; then
        fail "$jar contains classes from other modules:" $others
    fi
done

exit $status
