#!/usr/bin/env bash
# Build an Arch Linux pacman package (.pkg.tar.zst) for posprint.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

SKIP_TESTS=false
AS_ROOT=false
INSTALL=false

for arg in "$@"; do
  case "$arg" in
    --skip-tests) SKIP_TESTS=true ;;
    --asroot) AS_ROOT=true ;;
    --install) INSTALL=true ;;
    -h|--help)
      echo "Usage: $0 [--skip-tests] [--asroot] [--install]"
      echo "Builds packaging/arch/posprint-<ver>-<rel>-x86_64.pkg.tar.zst"
      echo "  --install   install the package with pacman after building"
      echo "On a TTY, missing build dependencies are offered for automatic install."
      echo "Without --install, prompts interactively when stdin is a TTY."
      echo "Uses rustup/cargo on PATH; runs makepkg --nodeps if pacman rust/cargo are absent."
      exit 0
      ;;
    *) echo "Unknown option: $arg"; exit 1 ;;
  esac
done

is_interactive() {
  [[ -t 0 ]]
}

ask_yes_no() {
  local prompt="$1"
  if ! is_interactive; then
    return 1
  fi
  local answer
  read -r -p "$prompt [y/N] " answer
  [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]]
}

want_install() {
  if [[ "$INSTALL" == "true" ]]; then
    return 0
  fi
  if ! is_interactive; then
    return 1
  fi
  ask_yes_no "Install the package now with pacman?"
}

# Ensure rustup toolchains are visible to makepkg's build().
if [[ -f "$HOME/.cargo/env" ]]; then
  # shellcheck source=/dev/null
  source "$HOME/.cargo/env"
fi

ensure_makepkg() {
  if command -v makepkg &>/dev/null; then
    return 0
  fi

  echo "makepkg not found (base-devel)."
  if ask_yes_no "Install base-devel with pacman now?"; then
    sudo pacman -S --needed --noconfirm base-devel
  else
    echo "Install manually: sudo pacman -S base-devel"
    exit 1
  fi

  if ! command -v makepkg &>/dev/null; then
    echo "makepkg still not found after install."
    exit 1
  fi
}

ensure_rust() {
  if command -v cargo &>/dev/null && command -v rustc &>/dev/null; then
    return 0
  fi

  echo "cargo/rustc not found."
  if ask_yes_no "Install Rust via rustup now?"; then
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    # shellcheck source=/dev/null
    source "$HOME/.cargo/env"
  elif ask_yes_no "Install pacman rust/cargo packages instead?"; then
    sudo pacman -S --needed --noconfirm rust
  else
    echo "Install via rustup (https://rustup.rs) or: sudo pacman -S rust"
    exit 1
  fi

  if ! command -v cargo &>/dev/null || ! command -v rustc &>/dev/null; then
    echo "Rust install finished but cargo/rustc still not on PATH. Open a new shell or: source \"\$HOME/.cargo/env\""
    exit 1
  fi
}

ensure_arch_build_deps() {
  if ! command -v pacman &>/dev/null; then
    return 0
  fi

  # Runtime/build libs commonly needed for egui + serialport (beyond base-devel).
  local pkgs=(
    pkgconf
    openssl
    libxkbcommon
    libxcb
    dbus
    wayland
    libx11
    fontconfig
    freetype2
    libglvnd
    git
    rsync
  )
  local missing=()
  local pkg
  for pkg in "${pkgs[@]}"; do
    if ! pacman -Q "$pkg" &>/dev/null; then
      missing+=("$pkg")
    fi
  done

  if [[ ${#missing[@]} -eq 0 ]]; then
    return 0
  fi

  echo "Missing pacman packages: ${missing[*]}"
  if ask_yes_no "Install them with pacman now?"; then
    sudo pacman -S --needed --noconfirm "${missing[@]}"
  else
    echo "Install manually, then re-run:"
    echo "  sudo pacman -S --needed ${missing[*]}"
    exit 1
  fi
}

ensure_makepkg
ensure_rust
ensure_arch_build_deps

# PKGBUILD lists pacman rust/cargo as makedepends. rustup installs don't register
# those packages, so skip dep resolution when the toolchain is already on PATH.
MAKEPKG_NODEPS=false
if ! pacman -Q rust &>/dev/null || ! pacman -Q cargo &>/dev/null; then
  echo "Note: pacman rust/cargo not installed; using toolchain on PATH ($(rustc --version))."
  echo "      makepkg will run with --nodeps."
  MAKEPKG_NODEPS=true
fi

if [[ "$SKIP_TESTS" != "true" ]]; then
  cargo test
fi

PKGVER="$(grep '^version' Cargo.toml | head -1 | sed -E 's/.*"([^"]+)".*/\1/')"
# makepkg refuses PKGBUILDs with Windows (CRLF) line endings.
sed -i "s/\r$//; s/^pkgver=.*/pkgver=${PKGVER}/" packaging/arch/PKGBUILD

cd packaging/arch
MAKEPKG_FLAGS=(-f --noconfirm)
if [[ "$AS_ROOT" == "true" ]]; then
  MAKEPKG_FLAGS+=(--asroot)
fi
if [[ "$MAKEPKG_NODEPS" == "true" ]]; then
  MAKEPKG_FLAGS+=(--nodeps)
fi
makepkg "${MAKEPKG_FLAGS[@]}"

shopt -s nullglob
PACKAGES=(posprint-"${PKGVER}"-*-x86_64.pkg.tar.zst)
shopt -u nullglob
if [[ ${#PACKAGES[@]} -eq 0 ]]; then
  echo "No package produced."
  exit 1
fi

echo "Arch package:"
ls -lh "${PACKAGES[@]}"

if want_install; then
  echo "Installing with pacman..."
  sudo pacman -U --noconfirm "${PACKAGES[@]}"
  echo "Installed."
fi
