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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
APT_UPDATED=0

usage() {
  cat <<'EOF'
Usage:
  scripts/bootstrap-ubuntu.sh [--no-install]

Installs the Ubuntu packages needed to build Ehwrj, then runs the full
Release verification and Windows x64 publish pipeline.

Options:
  --no-install   Skip apt installs and only run the verification/publish step.
EOF
}

NO_INSTALL=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --no-install)
      NO_INSTALL=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "error: unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [[ -r /etc/os-release ]]; then
  # shellcheck disable=SC1091
  . /etc/os-release
else
  echo "error: /etc/os-release not found; this script expects Ubuntu." >&2
  exit 1
fi

if [[ "${ID:-}" != "ubuntu" ]]; then
  echo "error: this bootstrap script expects Ubuntu, got '${ID:-unknown}'." >&2
  exit 1
fi

run_as_root() {
  if [[ "$(id -u)" -eq 0 ]]; then
    "$@"
    return
  fi

  if ! command -v sudo >/dev/null 2>&1; then
    echo "error: sudo is required when not running as root." >&2
    exit 1
  fi

  sudo "$@"
}

apt_install() {
  if [[ "$NO_INSTALL" -eq 1 ]]; then
    return
  fi

  if [[ "$APT_UPDATED" -eq 0 ]]; then
    run_as_root apt-get update
    APT_UPDATED=1
  fi

  run_as_root apt-get install -y "$@"
}

has_dotnet_8_sdk() {
  command -v dotnet >/dev/null 2>&1 && dotnet --list-sdks | awk '{print $1}' | grep -q '^8\.'
}

missing=()

if ! has_dotnet_8_sdk; then
  missing+=(dotnet-sdk-8.0)
fi

if ! command -v rg >/dev/null 2>&1; then
  missing+=(ripgrep)
fi

if [[ "${#missing[@]}" -gt 0 ]]; then
  if [[ "$NO_INSTALL" -eq 1 ]]; then
    echo "error: missing required tools: ${missing[*]}" >&2
    exit 1
  fi

  apt_install "${missing[@]}"
fi

if ! has_dotnet_8_sdk; then
  echo "error: dotnet 8 SDK is still unavailable after package installation." >&2
  exit 1
fi

if ! command -v rg >/dev/null 2>&1; then
  echo "error: ripgrep is still unavailable after package installation." >&2
  exit 1
fi

"$ROOT_DIR/scripts/publish-win-x64.sh"

echo
echo "Published Windows build:"
echo "  $ROOT_DIR/src/Ehwrj.App/bin/Release/net8.0/win-x64/publish/Ehwrj.exe"
