#!/usr/bin/env sh
# Naiscan installer (macOS / Linux).
# Checks for Python, installs it if missing (brew/apt/dnf/pacman — may prompt
# for your password), then installs Naiscan from the hosted archive.
# Review this script before running it. Override the source with NAISCAN_BASE.
set -e

BASE="${NAISCAN_BASE:-https://scanner.globusgroup.com}"
ZIP="$BASE/naiscan.zip"

echo "== Naiscan installer =="

PY=""
for c in python3 python; do
  if command -v "$c" >/dev/null 2>&1; then PY="$c"; break; fi
done

if [ -z "$PY" ]; then
  echo "Python not found — attempting to install it..."
  if command -v brew >/dev/null 2>&1; then
    brew install python
  elif command -v apt-get >/dev/null 2>&1; then
    sudo apt-get update && sudo apt-get install -y python3 python3-pip python3-venv
  elif command -v dnf >/dev/null 2>&1; then
    sudo dnf install -y python3 python3-pip
  elif command -v pacman >/dev/null 2>&1; then
    sudo pacman -Sy --noconfirm python python-pip
  else
    echo "Could not auto-install Python. Please install Python 3.11+ from"
    echo "https://www.python.org/downloads/ and re-run this script."
    exit 1
  fi
  PY=python3
fi

echo "Using $("$PY" --version 2>&1)"
"$PY" -m pip install --user --upgrade pip >/dev/null 2>&1 || true
"$PY" -m pip install --user "$ZIP"

echo ""
echo "Installed. Try:  naiscan --help"
echo "If 'naiscan' is not found, use:  $PY -m naiscan --help"
echo "(or add your user scripts dir, e.g. ~/.local/bin, to PATH)."
