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

# macOS prerequisite installer for Lomavuokraus development/testing.
# Installs core tools via Homebrew: Node.js 20, envsubst (gettext), kubectl, sops, Trivy, and Docker Desktop.
# Env opts:
#   SKIP_TRIVY=1  -> skip installing Trivy
#   SKIP_SOPS=1   -> skip installing sops

log() {
  echo "[mac-prereqs] $*"
}

warn() {
  echo "[mac-prereqs][warn] $*" >&2
}

require_macos() {
  if [[ "$(uname -s)" != "Darwin" ]]; then
    warn "This installer is for macOS only."
    exit 1
  fi
}

require_brew() {
  if command -v brew >/dev/null 2>&1; then
    return
  fi
  warn "Homebrew is required but not found."
  warn "Install Homebrew first, e.g.:"
  warn '  /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"'
  exit 1
}

install_formula() {
  local formula="$1"
  if brew list --formula "$formula" >/dev/null 2>&1; then
    log "Formula already installed: $formula"
    return
  fi
  log "Installing $formula..."
  brew install "$formula"
}

install_cask() {
  local cask="$1"
  if brew list --cask "$cask" >/dev/null 2>&1; then
    log "Cask already installed: $cask"
    return
  fi
  log "Installing cask $cask..."
  brew install --cask "$cask"
}

ensure_node20() {
  local current_major=""
  if command -v node >/dev/null 2>&1; then
    current_major="$(node -v | sed -E 's/^v([0-9]+).*/\1/')"
  fi

  if [[ -n "$current_major" && "$current_major" -ge 20 ]]; then
    log "Node.js already at v${current_major} (>=20); skipping install."
    return
  fi

  install_formula "node@20"
  log "Linking node@20 into PATH..."
  brew link --overwrite --force node@20
}

ensure_envsubst() {
  if command -v envsubst >/dev/null 2>&1; then
    log "envsubst already available."
    return
  fi

  install_formula "gettext"
  if ! command -v envsubst >/dev/null 2>&1; then
    log "Linking gettext to expose envsubst..."
    brew link --force gettext
  fi

  if ! command -v envsubst >/dev/null 2>&1; then
    warn "envsubst still not in PATH. Add $(brew --prefix)/opt/gettext/bin to PATH."
  fi
}

require_macos
require_brew

ensure_node20
ensure_envsubst
install_formula "kubectl"
[[ "${SKIP_SOPS:-0}" == "1" ]] || install_formula "sops"
[[ "${SKIP_TRIVY:-0}" == "1" ]] || install_formula "trivy"
install_cask "docker"

log "Done. Launch Docker.app once so the Docker daemon is available."
