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

apply=0
prefer_packagekit=1

usage() {
  cat <<'EOF'
Usage: Scripts/package/bootstrap-native-daemon.sh [--apply] [--no-packagekit]

Detects the host package manager and prints, or with --apply runs, the native
install command for the Burrow daemon package. This is the host-side bootstrap
equivalent the Flatpak GUI can point users at when PackageKit is unavailable.

This assumes the Burrow native repository for the detected package manager is
already configured. Repository setup should be explicit because it establishes
package trust roots.
EOF
}

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

run_or_print() {
  if [[ "$apply" == "1" ]]; then
    "$@"
  else
    printf '%q ' "$@"
    printf '\n'
  fi
}

if [[ "$prefer_packagekit" == "1" ]] && command -v pkcon >/dev/null 2>&1; then
  run_or_print pkcon install burrow
  exit 0
fi

if command -v apt-get >/dev/null 2>&1; then
  run_or_print sudo apt-get install burrow
elif command -v dnf >/dev/null 2>&1; then
  run_or_print sudo dnf install burrow
elif command -v zypper >/dev/null 2>&1; then
  run_or_print sudo zypper install burrow
elif command -v pacman >/dev/null 2>&1; then
  run_or_print sudo pacman -S burrow
elif command -v apk >/dev/null 2>&1; then
  run_or_print sudo apk add burrow
elif command -v xbps-install >/dev/null 2>&1; then
  run_or_print sudo xbps-install -S burrow
elif command -v eopkg >/dev/null 2>&1; then
  run_or_print sudo eopkg install burrow
elif command -v emerge >/dev/null 2>&1; then
  run_or_print sudo emerge --ask net-vpn/burrow
elif command -v swupd >/dev/null 2>&1; then
  run_or_print sudo swupd bundle-add burrow
elif command -v nix >/dev/null 2>&1; then
  run_or_print nix profile install git+https://git.burrow.net/hackclub/burrow
else
  echo "No supported native package manager found. Install Burrow through DEB, RPM, pacman, AUR, Flatpak GUI plus daemon package, or the NixOS flake." >&2
  exit 69
fi
