#!/bin/sh

# Check if lintian is available
if ! command -v lintian >/dev/null 2>&1; then
    echo "Warning: lintian not found. Skipping Lintian package validation."
    exit 0
fi

# Check if dpkg-deb is available
if ! command -v dpkg-deb >/dev/null 2>&1; then
    echo "Warning: dpkg-deb not found. Skipping Lintian package validation."
    exit 0
fi

# Go to the build directory
BUILD_DIR="@CMAKE_BINARY_DIR@"
cd "$BUILD_DIR" || exit 1

# Clean old build/packages to ensure clean permissions
rm -rf "${BUILD_DIR}/_CPack_DEB"

# Run CPack to generate the DEB package
echo "Generating Debian package using CPack..."
if ! "@CMAKE_CPACK_COMMAND@" -G DEB -B "${BUILD_DIR}/_CPack_DEB"; then
    echo "Failure: CPack failed to generate the DEB package."
    exit 1
fi

# Find the generated DEB package
DEB_PACKAGE=$(find "${BUILD_DIR}/_CPack_DEB" -maxdepth 1 -iname "*wxmaxima*.deb" | head -n 1)

if [ -z "$DEB_PACKAGE" ]; then
    echo "Failure: No generated DEB package found."
    exit 1
fi

echo "Running Lintian on $DEB_PACKAGE..."
# EXPECTED lint findings: we deliberately do NOT ship a copyright file, a
# changelog, or pre-compressed manpages in the install tree, because those
# collide with the Debian maintainer's own dh_* tooling (dh_installdocs /
# dh_installchangelogs / dh_compress) -- see data/CMakeLists.txt and
# src/CMakeLists.txt. Those produce no-copyright-file / no-changelog /
# uncompressed-manual-page on OUR CPack .deb, which is fine. We suppress ONLY
# those known tags so that ANY OTHER lintian error still fails the test and
# alerts us to a real regression.
EXPECTED_TAGS="no-copyright-file,no-changelog,uncompressed-manual-page"
echo "(Suppressing expected tags: $EXPECTED_TAGS)"
# Run lintian, checking for errors only (warnings are acceptable, but errors fail the test)
if lintian -E --fail-on error --suppress-tags "$EXPECTED_TAGS" "$DEB_PACKAGE"; then
    echo "Success: Lintian detected no unexpected errors in the DEB package."
    exit 0
else
    echo "Failure: Lintian detected unexpected errors in the DEB package."
    exit 1
fi
