#!/usr/bin/env sh
set -euo pipefail

say() { printf "%s\n" "$*"; }
ok()  { printf " OK\n"; }

say ""
say "==> Installing PiaPulse (global bootstrap)"

# Detect platform
OS=$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]' || echo unknown)
ARCH=$(uname -m 2>/dev/null || echo unknown)
case "$ARCH" in
  x86_64|amd64) ARCH=amd64 ;;
  arm64|aarch64) ARCH=arm64 ;;
  *) say "Unsupported arch: $ARCH" >&2; exit 1 ;;
esac

case "$OS" in
  linux) OS=linux ;;
  darwin) OS=darwin ;;
  msys*|mingw*|cygwin*) say "Windows: use install.ps1" >&2; exit 1 ;;
  *) say "Unsupported OS: $OS" >&2; exit 1 ;;
esac

# Detect WSL and guide to PowerShell unless explicitly allowed
if [ "$OS" = linux ] && grep -qiE '(microsoft|wsl)' /proc/version 2>/dev/null; then
  if [ "${PIAPULSE_ALLOW_WSL:-}" != "1" ]; then
    say "WSL detected. Please run on Windows PowerShell:"
    say "  iwr -useb https://install.piapulse.dev | iex"
    exit 1
  fi
fi

BASE=${PIAPULSE_DL_BASE:-https://install.piapulse.dev}
VERSION=${PIAPULSE_VERSION:-latest}

# Choose install dir to support update-in-place when re-running
if [ -n "${PIAPULSE_BIN_DIR-}" ]; then
  BIN_DIR="$PIAPULSE_BIN_DIR"
else
  # Prefer existing installed location if found in PATH and writable
  EXIST_PATH=""
  if command -v piapulse >/dev/null 2>&1; then
    EXIST_PATH=$(command -v piapulse 2>/dev/null || true)
  fi
  if [ -n "$EXIST_PATH" ]; then
    EXIST_DIR=$(dirname "$EXIST_PATH")
    if [ -w "$EXIST_DIR" ]; then
      BIN_DIR="$EXIST_DIR"
    fi
  fi
  # Otherwise, first writable dir in PATH
  if [ -z "${BIN_DIR:-}" ]; then
    OLD_IFS="$IFS"; IFS=":"
    for d in $PATH; do
      [ -z "$d" ] && continue
      if [ -d "$d" ] && [ -w "$d" ]; then
        BIN_DIR="$d"; break
      fi
    done
    IFS="$OLD_IFS"
  fi
  # Fallbacks
  if [ -z "${BIN_DIR:-}" ]; then
    if printf "%s" ":$PATH:" | grep -q ":$HOME/.local/bin:"; then
      BIN_DIR="$HOME/.local/bin"
    else
      BIN_DIR="$HOME/.piapulse/bin"
    fi
  fi
fi
mkdir -p "$BIN_DIR"

say "    Platform: $OS/$ARCH"

# Resolve numeric latest
if [ "$VERSION" = "latest" ]; then
  if command -v curl >/dev/null 2>&1; then
    LV=$(curl -fsSL "$BASE/latest.txt" 2>/dev/null || true)
  elif command -v wget >/dev/null 2>&1; then
    LV=$(wget -q -O - "$BASE/latest.txt" 2>/dev/null || true)
  else
    LV=""
  fi
  LV=$(printf "%s" "$LV" | tr -d '\r' | tr -d '\n')
  if [ -n "${LV:-}" ]; then VERSION="$LV"; fi
fi
say "    Version : $VERSION"

# Determine subdir to match R2 layout
case "$OS" in
  linux)
    if [ "$ARCH" = "amd64" ]; then
      SUB="linux-x64"
    else
      SUB="linux-$ARCH"
    fi
    ;;
  darwin)
    if [ "$ARCH" = "amd64" ]; then
      SUB="darwin-x64"
    else
      SUB="darwin-$ARCH"
    fi
    ;;
esac

# Candidate URLs (prefer non-versioned bootstrap; fall back to versioned layouts)
TS=$(date +%s)
CANDIDATES="\
$BASE/bootstrap/$SUB/piapulseSET?t=$TS \
$BASE/bootstrap/$SUB/bootstrap?t=$TS \
$BASE/bootstrap/$SUB/piapulse?t=$TS \
$BASE/$VERSION/bootstrap/$SUB/piapulseSET?t=$TS \
$BASE/$VERSION/bootstrap/$SUB/bootstrap?t=$TS \
$BASE/$VERSION/bootstrap/$SUB/piapulse?t=$TS \
$BASE/bootstrap/$VERSION/$SUB/piapulseSET?t=$TS \
$BASE/bootstrap/$VERSION/$SUB/bootstrap?t=$TS \
$BASE/bootstrap/$VERSION/$SUB/piapulse?t=$TS"

TMP_DIR=$(mktemp -d)
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT INT HUP

fetch() {
  url="$1"; out="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -H 'User-Agent: PiaPulse-Installer/1.0 (+https://piapulse.dev)' -o "$out" "$url" && return 0
  elif command -v wget >/dev/null 2>&1; then
    wget --header='User-Agent: PiaPulse-Installer/1.0 (+https://piapulse.dev)' -q -O "$out" "$url" && return 0
  fi
  return 1
}

say "- Downloading bootstrap ..." | tr -d '\n'
ok=false
for u in $CANDIDATES; do
  name=$(basename "$u")
  out="$TMP_DIR/$name"
  if fetch "$u" "$out"; then
    SRC="$out"
    ok=true
    break
  fi
done
if [ "$ok" != "true" ]; then
  say " failed"
  say "No downloadable bootstrap for $OS/$ARCH at $BASE" >&2
  exit 1
fi
ok

say "- Installing to $BIN_DIR ..." | tr -d '\n'
install -m 0755 "$SRC" "$BIN_DIR/piapulseSET"
ok

# Add to PATH if missing
case ":$PATH:" in
  *:"$BIN_DIR":*) ;;
  *)
    SHELL_RC="$HOME/.bashrc"
    if [ -n "${ZSH_VERSION-}" ]; then SHELL_RC="$HOME/.zshrc"; fi
    printf 'export PATH="%s:$PATH"\n' "$BIN_DIR" >> "$SHELL_RC"
    say "- PATH updated in $SHELL_RC"
    ;;
esac

say "- Done"
say "  Run: piapulseSET create <app-name>"
say ""
