#!/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 "On a TTY, missing build dependencies are offered for automatic install."
      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

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 .deb now with apt?"
}

# Make rustup toolchains visible when installed but not yet on PATH.
if [[ -f "$HOME/.cargo/env" ]]; then
  # shellcheck source=/dev/null
  source "$HOME/.cargo/env"
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"
  else
    echo "Install Rust from https://rustup.rs (or your distro packages), then re-run."
    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_debian_build_deps() {
  if ! command -v apt-get &>/dev/null; then
    return 0
  fi

  local pkgs=(
    build-essential
    pkg-config
    libxcb-render0-dev
    libxcb-shape0-dev
    libxcb-xfixes0-dev
    libxkbcommon-dev
    libssl-dev
    libudev-dev
  )
  local missing=()
  local pkg
  for pkg in "${pkgs[@]}"; do
    if ! dpkg -s "$pkg" &>/dev/null; then
      missing+=("$pkg")
    fi
  done

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

  echo "Missing apt packages: ${missing[*]}"
  if ask_yes_no "Install them with apt now?"; then
    sudo apt-get update
    sudo apt-get install -y "${missing[@]}"
  else
    echo "Install manually, then re-run:"
    echo "  sudo apt-get install -y ${missing[*]}"
    exit 1
  fi
}

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

  echo "cargo-deb not found (needed for --deb)."
  if ask_yes_no "Install cargo-deb with cargo now?"; then
    cargo install cargo-deb --locked
  else
    echo "Install manually: cargo install cargo-deb --locked"
    exit 1
  fi
}

ensure_rust
ensure_debian_build_deps

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
  ensure_cargo_deb
  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
