#!/usr/bin/env bash
# Single source of truth for sethLabels build dependencies on Debian-family Linux.
#
# When SOURCED:   exposes SETHLABELS_DEPS array (no side effects).
# When EXECUTED:  verifies each dep is installed; prints actionable
#                 `sudo apt install ...` command on missing deps; exits 1.
#                 On clean state, prints "All build dependencies present." and exits 0.
#
# Spec: sethlabels-docs/specs/2026-04-29-packaging-design.md §5.1
set -euo pipefail

SETHLABELS_DEPS=(
  build-essential cmake ninja-build pkg-config
  qt6-base-dev qt6-base-dev-tools
  qt6-svg-dev
  qt6-tools-dev qt6-tools-dev-tools
  qt6-l10n-tools
  libqt6printsupport6 libqt6svg6 libqt6widgets6 libqt6xml6 libqt6gui6
  libqt6concurrent6 libqt6core6t64 libqt6test6
  zlib1g-dev libqrencode-dev libzint-dev
  file dpkg-dev fakeroot
  wget
  bats
  xvfb
)

# Detect sourced vs. executed.
# When sourced: BASH_SOURCE[0] != $0
# When executed: BASH_SOURCE[0] == $0
if [ "${BASH_SOURCE[0]}" != "${0}" ]; then
  return 0 2>/dev/null || exit 0
fi

# --- Executed path ---

# Sanity check the build host
if [ ! -f /etc/os-release ]; then
  echo "WARNING: /etc/os-release missing; not Debian-family. This script is designed for Debian 13 / Ubuntu LTS." >&2
fi

if [ -f /etc/os-release ]; then
  . /etc/os-release
  if [[ "${ID:-}" != "debian" && "${ID:-}" != "ubuntu" ]] && [[ "${ID_LIKE:-}" != *debian* && "${ID_LIKE:-}" != *ubuntu* ]]; then
    echo "WARNING: not running on Debian or Ubuntu (detected ID='${ID:-unknown}'). Build deps may differ." >&2
  fi
fi

missing=()
for pkg in "${SETHLABELS_DEPS[@]}"; do
  if ! dpkg-query -W -f='${Status}' "$pkg" 2>/dev/null | grep -q "install ok installed"; then
    missing+=("$pkg")
  fi
done

if [ "${#missing[@]}" -gt 0 ]; then
  echo "Missing build dependencies (${#missing[@]}):"
  for p in "${missing[@]}"; do
    echo "  - $p"
  done
  echo ""
  echo "Install with:"
  echo "  sudo apt install -y ${missing[*]}"
  exit 1
fi

echo "All build dependencies present (${#SETHLABELS_DEPS[@]} packages verified)."
