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

SCRIPT_NAME="$(basename "$0")"

PKGCONFIG_MODULES=(
  "webkit2gtk-4.1"
  "libsoup-3.0"
  "javascriptcoregtk-4.1"
)

DEBIAN_PACKAGES=(
  "pkg-config"
  "libwebkit2gtk-4.1-dev"
  "libsoup-3.0-dev"
  "libjavascriptcoregtk-4.1-dev"
)

usage() {
  cat <<USAGE
Usage: $SCRIPT_NAME [check|install|help]

Commands:
  check    Check required Linux system dependencies for Tauri build
  install  Install dependencies (Debian/Ubuntu only)
  help     Show this help
USAGE
}

print_missing_hint() {
  echo
  echo "To install on Debian/Ubuntu, run:"
  echo "  sudo apt-get update"
  echo "  sudo apt-get install -y ${DEBIAN_PACKAGES[*]}"
}

check_deps() {
  local missing=()

  if ! command -v pkg-config >/dev/null 2>&1; then
    missing+=("pkg-config (command not found)")
  else
    for module in "${PKGCONFIG_MODULES[@]}"; do
      if ! pkg-config --exists "$module"; then
        missing+=("$module")
      fi
    done
  fi

  if [ "${#missing[@]}" -eq 0 ]; then
    echo "All required system dependencies are installed."
    return 0
  fi

  echo "Missing system dependencies:"
  for dep in "${missing[@]}"; do
    echo "  - $dep"
  done

  print_missing_hint
  return 1
}

install_deps_debian() {
  local prefix=()

  if [ "${EUID}" -ne 0 ]; then
    if command -v sudo >/dev/null 2>&1; then
      prefix=(sudo)
    else
      echo "Error: need root privileges (run as root or install sudo)." >&2
      return 1
    fi
  fi

  echo "Installing Debian/Ubuntu packages: ${DEBIAN_PACKAGES[*]}"
  "${prefix[@]}" apt-get update
  "${prefix[@]}" apt-get install -y "${DEBIAN_PACKAGES[@]}"
}

install_deps() {
  if [ ! -f /etc/os-release ]; then
    echo "Unsupported OS: /etc/os-release not found." >&2
    print_missing_hint
    return 1
  fi

  # shellcheck source=/dev/null
  . /etc/os-release

  case "${ID:-}" in
    ubuntu|debian|linuxmint|pop)
      install_deps_debian
      ;;
    *)
      if echo "${ID_LIKE:-}" | grep -qi "debian"; then
        install_deps_debian
      else
        echo "Unsupported distro for auto-install: ${ID:-unknown}" >&2
        echo "Please install packages manually for your distro."
        print_missing_hint
        return 1
      fi
      ;;
  esac

  echo
  check_deps
}

main() {
  local cmd="${1:-check}"

  case "$cmd" in
    check)
      check_deps
      ;;
    install)
      install_deps
      ;;
    help|-h|--help)
      usage
      ;;
    *)
      echo "Unknown command: $cmd" >&2
      usage >&2
      return 2
      ;;
  esac
}

main "$@"
