#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<USAGE
Usage: $0

Installs required build dependencies on Debian/Ubuntu using apt.

Environment:
  DEPS_AUTO   (default: 1)  set to 0 to only print missing packages and exit non-zero
  APT_YES     (default: 1)  set to 0 to run apt without -y
USAGE
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

DEPS_AUTO="${DEPS_AUTO:-1}"
APT_YES="${APT_YES:-1}"

# Must have apt
if ! command -v apt-get >/dev/null 2>&1; then
  echo "ERROR: apt-get not found. This script supports Debian/Ubuntu only." >&2
  exit 1
fi

# Basic distro check (soft)
if [[ -r /etc/os-release ]]; then
  . /etc/os-release
  case "${ID:-}" in
    debian|ubuntu|linuxmint|pop) : ;;
    *)
      echo "WARN: Detected ID=${ID:-unknown}. Proceeding anyway (apt-based system assumed)." >&2
      ;;
  esac
fi

# Packages needed to build UW-IMAP 2007f with modern toolchains
PKGS=(
  build-essential
  autoconf
  automake
  libtool
  pkg-config
  libssl-dev
  libpam0g-dev
  libc6-dev
  libcrypt-dev
  bison
  flex
  patch
  ca-certificates
)

missing=()
for p in "${PKGS[@]}"; do
  if dpkg -s "$p" >/dev/null 2>&1; then
    continue
  fi
  missing+=( "$p" )
done

if (( ${#missing[@]} == 0 )); then
  echo "==> Dependencies already satisfied."
  exit 0
fi

echo "==> Missing packages:"
printf '  - %s\n' "${missing[@]}"

if [[ "$DEPS_AUTO" != "1" ]]; then
  echo "DEPS_AUTO=0 -> not installing automatically." >&2
  exit 2
fi

# Choose privilege escalation
SUDO=""
if [[ "$(id -u)" -ne 0 ]]; then
  if command -v sudo >/dev/null 2>&1; then
    SUDO="sudo"
  else
    echo "ERROR: Not running as root and sudo not found." >&2
    exit 1
  fi
fi

yesflag=()
if [[ "$APT_YES" == "1" ]]; then
  yesflag=( -y )
fi

echo "==> Updating apt index"
$SUDO apt-get update

echo "==> Installing dependencies"
$SUDO apt-get install "${yesflag[@]}" "${missing[@]}"

echo "==> Done."
