#!/usr/bin/env bash
# Install the current PathMX beta launcher. Requires Bash, curl, and (for Bun) unzip.
# Keep this channel/minimum aligned with pathmx/core/package.json.
set -euo pipefail

fail() { printf 'PathMX: %s\n' "$*" >&2; exit 1; }

main() {
  case "${1:-}" in
    --help|-h)
      printf 'Usage: bash install.sh\nInstalls Bun when missing and the newest @pathmx/core@beta launcher.\n'
      return ;;
    '') ;;
    *) fail 'Unknown argument. Usage: bash install.sh' ;;
  esac
  case "$(uname -s)" in
    Darwin|Linux) ;;
    *) fail 'Use this installer on macOS, Linux, or WSL. On Windows, install Bun from https://bun.sh then run: bun add --global @pathmx/core@beta' ;;
  esac
  [ "$(id -u)" != 0 ] || fail 'Run as your normal user, without sudo.'
  [ -n "${HOME:-}" ] || fail 'HOME must be set.'

  local bun_bin bun_version major minor global_bin original_path
  original_path=$PATH
  bun_bin=$(command -v bun || true)
  if [ -z "$bun_bin" ] && [ -x "${BUN_INSTALL:-$HOME/.bun}/bin/bun" ]; then
    bun_bin="${BUN_INSTALL:-$HOME/.bun}/bin/bun"
  fi

  # Work outside the caller's project: do not load its bunfig, .env, or pinned CLI.
  install_tmp=$(mktemp -d "${TMPDIR:-/tmp}/pathmx-install.XXXXXXXX")
  trap 'rm -rf -- "$install_tmp"' EXIT
  cd "$install_tmp"

  if [ -z "$bun_bin" ]; then
    command -v curl >/dev/null || fail 'Install curl, then run this installer again.'
    command -v unzip >/dev/null || fail 'Install unzip with your system package manager, then run this installer again.'
    printf 'Installing Bun with its official installer…\n'
    # Download completely before executing; never execute a partial response.
    curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 3 \
      https://bun.com/install -o bun-install.sh || fail 'Could not download the Bun installer.'
    bash bun-install.sh || fail 'Bun installation failed.'
    bun_bin="${BUN_INSTALL:-$HOME/.bun}/bin/bun"
  fi

  bun_version=$("$bun_bin" --version) || fail 'Bun could not run. Reinstall Bun from https://bun.sh.'
  if [[ "$bun_version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
    major=${BASH_REMATCH[1]}
    minor=${BASH_REMATCH[2]}
    (( major > 1 || (major == 1 && minor >= 4) )) || \
      fail "Bun $bun_version is too old; 1.4.0+ is required. Upgrade with your package manager (brew upgrade bun for Homebrew), or bun upgrade for a script install, then rerun."
  else
    fail "Expected a stable Bun version, received: $bun_version. Install stable Bun 1.4.0 or newer."
  fi
  export PATH="$(dirname "$bun_bin"):$PATH"
  printf 'Using Bun %s. Installing the latest PathMX beta…\n' "$bun_version"
  "$bun_bin" --no-env-file add --global @pathmx/core@beta || fail 'CLI installation failed. Check the output above and rerun.'
  global_bin=$("$bun_bin" --no-env-file pm bin --global) || fail 'Could not locate the global executable directory.'
  [ -x "$global_bin/pmx" ] || fail "Installation did not create $global_bin/pmx."
  export PATH="$global_bin:$PATH"
  "$global_bin/pmx" --version || fail 'The installed pmx command failed its version check.'
  printf '\nPathMX is installed.\n'
  local directory
  for directory in "$(dirname "$bun_bin")" "$global_bin"; do
    case ":$original_path:" in
      *":$directory:"*) ;;
      *)
        printf 'Add this directory to your shell PATH: %s\n' "$directory"
        original_path="$directory:$original_path" ;;
    esac
  done
  printf 'Open a new terminal, then run: pmx init my-site\n'
}

# A truncated streamed download cannot execute the body before it is fully parsed.
main "$@"
