#!/bin/bash
# Ensure build dependencies are installed.
# Source this file from build scripts: source "$SCRIPT_DIR/ensure-deps.sh"
#
# Checks for: node, pnpm, bun, nfpm
# Auto-installs missing tools. Uses npm for pnpm/bun, downloads nfpm binary.

NFPM_VERSION="${NFPM_VERSION:-2.45.0}"

_ensure_node() {
  if command -v node &>/dev/null; then
    return
  fi

  echo "ERROR: Node.js is required but not installed."
  if command -v dnf &>/dev/null; then
    echo "  Install with: sudo dnf install nodejs"
  elif command -v apt &>/dev/null; then
    echo "  Install with: sudo apt install nodejs npm"
  else
    echo "  Install from: https://nodejs.org/"
  fi
  exit 1
}

_ensure_pnpm() {
  if command -v pnpm &>/dev/null; then
    return
  fi

  echo "==> pnpm not found, installing..."
  if command -v corepack &>/dev/null; then
    corepack enable
    corepack prepare pnpm@9.15.0 --activate
  else
    npm install -g pnpm
  fi

  # Verify
  if ! command -v pnpm &>/dev/null; then
    echo "ERROR: pnpm installation failed."
    echo "  Try manually: npm install -g pnpm"
    exit 1
  fi
  echo "    Installed pnpm $(pnpm --version)"
}

_ensure_bun() {
  if command -v bun &>/dev/null; then
    return
  fi

  echo "==> bun not found, installing..."
  # bun's official install script handles both amd64 and arm64
  curl -fsSL https://bun.sh/install | bash

  # Add to PATH for this session
  export PATH="$HOME/.bun/bin:$PATH"

  if ! command -v bun &>/dev/null; then
    echo "ERROR: bun installation failed."
    echo "  Try manually: curl -fsSL https://bun.sh/install | bash"
    exit 1
  fi
  echo "    Installed bun $(bun --version)"
}

_ensure_nfpm() {
  if command -v nfpm &>/dev/null; then
    return
  fi

  echo "==> nfpm not found, installing v${NFPM_VERSION}..."

  # Detect host arch for the nfpm binary itself (not the target arch)
  local dl_arch
  case "$(uname -m)" in
    x86_64)  dl_arch="x86_64" ;;
    aarch64) dl_arch="arm64" ;;
    arm64)   dl_arch="arm64" ;;
    *)       dl_arch="x86_64" ;;
  esac

  local url="https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_Linux_${dl_arch}.tar.gz"
  local install_dir="$HOME/.local/bin"
  mkdir -p "$install_dir"

  curl -sL -o /tmp/nfpm.tar.gz "$url"
  tar xzf /tmp/nfpm.tar.gz -C "$install_dir" nfpm
  rm -f /tmp/nfpm.tar.gz

  export PATH="$install_dir:$PATH"

  if ! command -v nfpm &>/dev/null; then
    echo "ERROR: nfpm installation failed."
    echo "  Download manually from: https://github.com/goreleaser/nfpm/releases"
    exit 1
  fi
  echo "    Installed nfpm $(nfpm --version) to $install_dir"
}

_ensure_npm_deps() {
  if [ -d node_modules ]; then
    return
  fi

  echo "==> node_modules not found, running pnpm install..."
  pnpm install --frozen-lockfile
}

ensure_build_deps() {
  echo "==> Checking build dependencies..."
  _ensure_node
  _ensure_pnpm
  _ensure_bun
  _ensure_nfpm
  _ensure_npm_deps
  echo "    All build dependencies OK"
  echo ""
}
