#!/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 "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

want_install() {
  if [[ "$INSTALL" == "true" ]]; then
    return 0
  fi
  if [[ ! -t 0 ]]; then
    return 1
  fi
  local answer
  read -r -p "Install the package now with pacman? [y/N] " answer
  [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]]
}

if ! command -v makepkg &>/dev/null; then
  echo "makepkg not found. On Arch, install base-devel: sudo pacman -S base-devel"
  exit 1
fi

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

if ! command -v cargo &>/dev/null || ! command -v rustc &>/dev/null; then
  echo "cargo/rustc not found. Install via rustup (https://rustup.rs) or: sudo pacman -S rust"
  exit 1
fi

# 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
