#!/bin/sh
set -e

PASS=0
FAIL=0

ok()  { echo "OK: $*";  PASS=$((PASS + 1)); }
fail(){ echo "FAIL: $*"; FAIL=$((FAIL + 1)); }

# 1. Binary is present and executable
if [ -x "$(command -v ncmpcpp)" ]; then
    ok "ncmpcpp binary found in PATH"
else
    fail "ncmpcpp binary not found or not executable"
fi

# 2. --version exits cleanly and reports the package name
VERSION_OUT=$(ncmpcpp --version 2>&1)
if echo "$VERSION_OUT" | grep -q "^ncmpcpp"; then
    ok "--version reports ncmpcpp"
else
    fail "--version output did not start with 'ncmpcpp': $VERSION_OUT"
fi

# 3. --help exits 0 and mentions expected flags
HELP_OUT=$(ncmpcpp --help 2>&1)
if echo "$HELP_OUT" | grep -q -- "--version"; then
    ok "--help output mentions --version"
else
    fail "--help output missing --version flag"
fi
if echo "$HELP_OUT" | grep -q -- "--config"; then
    ok "--help output mentions --config"
else
    fail "--help output missing --config flag"
fi

# 4. Optional screens compiled in
for feature in "tag editor" "outputs" "visualizer" "clock"; do
    if echo "$VERSION_OUT" | grep -q "$feature"; then
        ok "optional screen compiled in: $feature"
    else
        fail "optional screen missing: $feature"
    fi
done

# 5. Support libraries compiled in
for lib in fftw ncurses taglib; do
    if echo "$VERSION_OUT" | grep -q "$lib"; then
        ok "built with support for: $lib"
    else
        fail "missing support for: $lib"
    fi
done

# 6. --ignore-config-errors suppresses error on unknown option
TMPCONF=$(mktemp)
echo "this_is_not_a_valid_option = true" > "$TMPCONF"
if ncmpcpp --config "$TMPCONF" --ignore-config-errors --help > /dev/null 2>&1; then
    ok "--ignore-config-errors suppresses unknown-option error"
else
    fail "--ignore-config-errors did not suppress error for invalid config"
fi
rm -f "$TMPCONF"

# 7. No custom RUNPATH in the binary (lintian: custom-library-search-path)
BINARY=$(command -v ncmpcpp)
RUNPATH=$(readelf -d "$BINARY" 2>/dev/null | grep -i 'runpath\|rpath' || true)
if [ -z "$RUNPATH" ]; then
    ok "binary has no RUNPATH/RPATH entries"
else
    fail "binary has unexpected RUNPATH/RPATH: $RUNPATH"
fi

echo ""
echo "Results: $PASS passed, $FAIL failed"
[ "$FAIL" -eq 0 ]
