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

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

PKGVER="$(grep '^version' Cargo.toml | head -1 | sed -E 's/.*"([^"]+)".*/\1/')"
sed -i "s/^pkgver=.*/pkgver=${PKGVER}/" packaging/arch/PKGBUILD

cd packaging/arch
MAKEPKG_FLAGS=(-f --noconfirm)
if [[ "$AS_ROOT" == "true" ]]; then
  MAKEPKG_FLAGS+=(--asroot)
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
