#!/usr/bin/env bash
# Build the sethLabels .deb package.
#
# Pipeline (spec §5.2):
#   1. sanity check build host (Debian/Ubuntu, deps present)
#   2. strict-zero guardrail
#   3. compute version
#   4. out-of-tree cmake build
#   5. CPack with overrides
#   6. inline smoke tests T1, T2
#   7. print artifact path for the operator
#
# Spec: sethlabels-docs/specs/2026-04-29-packaging-design.md §5.2
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$REPO_ROOT"

echo "==> [1/6] Sanity check build host"
"$REPO_ROOT/scripts/lib/deps-debian.sh"

echo "==> [2/6] Strict-zero guardrail"
"$REPO_ROOT/scripts/check-no-upstream-edits.sh"

echo "==> [3/6] Compute version"
VERSION="$("$REPO_ROOT/scripts/compute-version.sh")"
echo "    VERSION = $VERSION"

echo "==> [4/6] Out-of-tree cmake build"
BUILD_DIR="$REPO_ROOT/build/deb"
rm -rf "${BUILD_DIR:?BUILD_DIR must not be empty}"
mkdir -p "$BUILD_DIR"
cmake -S "$REPO_ROOT" -B "$BUILD_DIR" -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build "$BUILD_DIR" --parallel

echo "==> [5/6] CPack DEB generation"
# shellcheck disable=SC1091
source "$REPO_ROOT/packaging/deb-metadata.env"

cd "$BUILD_DIR"
cpack -G DEB \
  -D CPACK_PACKAGE_NAME="$PACKAGE_NAME" \
  -D CPACK_PACKAGE_VERSION="$VERSION" \
  -D CPACK_DEBIAN_PACKAGE_NAME="$PACKAGE_NAME" \
  -D CPACK_DEBIAN_PACKAGE_MAINTAINER="$MAINTAINER" \
  -D CPACK_DEBIAN_PACKAGE_SECTION="$SECTION" \
  -D CPACK_DEBIAN_PACKAGE_HOMEPAGE="$HOMEPAGE" \
  -D CPACK_DEBIAN_PACKAGE_SHLIBDEPS=ON \
  -D CPACK_DEBIAN_FILE_NAME=DEB-DEFAULT
cd "$REPO_ROOT"

# Resolve the actual artifact filename (CPack uses DEB-DEFAULT naming convention).
DEB_ARTIFACT=$(ls "$BUILD_DIR"/${PACKAGE_NAME}_*.deb 2>/dev/null | head -1)
if [ -z "$DEB_ARTIFACT" ] || [ ! -f "$DEB_ARTIFACT" ]; then
  echo "ERROR: expected .deb artifact not found in $BUILD_DIR" >&2
  ls -la "$BUILD_DIR" >&2
  exit 1
fi

echo "==> [6/6] Smoke tests"

# T1: dpkg-deb --info parses, version field matches.
echo "    T1: dpkg-deb --info"
T1_OUT=$(dpkg-deb --info "$DEB_ARTIFACT")
if ! echo "$T1_OUT" | grep -qE "^ Version: ${VERSION}$"; then
  echo "ERROR: T1 failed — version field in .deb does not match \$VERSION=$VERSION" >&2
  echo "$T1_OUT" >&2
  exit 1
fi
echo "    T1: PASS"

# T2: dpkg-deb --contents includes both binaries.
echo "    T2: dpkg-deb --contents"
T2_OUT=$(dpkg-deb --contents "$DEB_ARTIFACT")
if ! echo "$T2_OUT" | grep -q '/usr/bin/glabels-qt'; then
  echo "ERROR: T2 failed — /usr/bin/glabels-qt missing from .deb" >&2
  exit 1
fi
if ! echo "$T2_OUT" | grep -q '/usr/bin/glabels-batch-qt'; then
  echo "ERROR: T2 failed — /usr/bin/glabels-batch-qt missing from .deb" >&2
  exit 1
fi
echo "    T2: PASS"

# Optional: lintian (warnings-only, non-fatal during battle-test).
if command -v lintian >/dev/null 2>&1; then
  echo "    lintian (advisory):"
  lintian "$DEB_ARTIFACT" || true
fi

echo ""
echo "Artifact: $DEB_ARTIFACT"
