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

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

BUILD_DEB=false
SKIP_TESTS=false
INSTALL=false

for arg in "$@"; do
  case "$arg" in
    --deb) BUILD_DEB=true ;;
    --skip-tests) SKIP_TESTS=true ;;
    --install) INSTALL=true ;;
    -h|--help)
      echo "Usage: $0 [--deb] [--skip-tests] [--install]"
      echo "Builds target/release/posprint (and optionally a .deb)."
      echo "  --deb       also build a Debian package with cargo-deb"
      echo "  --install   install the .deb with apt after building (implies --deb)"
      echo "Without --install, prompts interactively for .deb install when stdin is a TTY."
      exit 0
      ;;
    *) echo "Unknown option: $arg"; exit 1 ;;
  esac
done

if [[ "$INSTALL" == "true" ]]; then
  BUILD_DEB=true
fi

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

echo "Building posprint for Linux (x86_64)..."

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

cargo build --release
BIN="$ROOT/target/release/posprint"
echo "OK: $BIN"
ls -lh "$BIN"

if [[ "$BUILD_DEB" == "true" ]]; then
  if ! command -v cargo-deb &>/dev/null; then
    echo "Installing cargo-deb..."
    cargo install cargo-deb --locked
  fi
  cargo deb
  shopt -s nullglob
  DEBS=("$ROOT"/target/debian/*.deb)
  shopt -u nullglob
  if [[ ${#DEBS[@]} -eq 0 ]]; then
    echo "No .deb produced."
    exit 1
  fi
  echo "Debian packages:"
  ls -lh "${DEBS[@]}"

  if want_install; then
    echo "Installing with apt..."
    # Relative path so apt treats it as a local package file.
    sudo apt-get install -y "${DEBS[@]}"
    echo "Installed."
  fi
fi
