#!/bin/sh

set -eu

OS="$(uname -s)"

die() {
  printf 'Fehler: %s\n' "$*" >&2
  exit 1
}

have() {
  command -v "$1" >/dev/null 2>&1
}

check_prerequisites() {
  case "$OS" in
  Darwin)
    if ! have brew; then
      die "Homebrew ist nicht installiert."
    fi
    ;;
  FreeBSD)
    if ! have doas; then
      die "doas ist nicht installiert."
    fi
    ;;
  *)
    die "Nicht unterstütztes Betriebssystem: $OS"
    ;;
  esac
}

setup_homebrew_env() {
  case "$OS" in
  Darwin)
    export HOMEBREW_NO_AUTO_UPDATE=1
    export HOMEBREW_NO_INSTALL_CLEANUP=1
    ;;
  esac
}

install_pkg() {
  binary="$1"
  package="$2"

  if have "$binary"; then
    printf "✓ %-32s vorhanden\n" "$binary"
    return
  fi

  printf "→ Installiere %s\n" "$package"

  case "$OS" in
  Darwin)
    brew install "$package"
    ;;
  FreeBSD)
    doas pkg install -y "$package"
    ;;
  esac
}

install_npm() {
  binary="$1"
  package="$2"

  if have "$binary"; then
    printf "✓ %-32s vorhanden\n" "$binary"
    return
  fi

  if ! have npm; then
    die "npm wurde nicht gefunden."
  fi

  printf "→ Installiere npm-Paket %s\n" "$package"
  npm install -g "$package"
}

install_prerequisites() {
  install_pkg curl curl
  install_pkg git git
  install_pkg node node
}

install_formatters() {
  install_pkg gawk gawk
  install_pkg jq jq
  install_npm prettier prettier
  install_pkg ruff ruff
  install_pkg shfmt shfmt
  install_pkg stylua stylua
  install_pkg yamlfmt yamlfmt

  case "$OS" in
  Darwin)
    install_pkg clang-format clang-format
    ;;
  FreeBSD)
    install_pkg xmllint libxml2
    ;;
  esac
}

install_tools() {
  install_pkg rg ripgrep

  case "$OS" in
  Darwin)
    install_pkg gmake make
    install_pkg fd fd
    install_pkg tree-sitter tree-sitter
    ;;
  FreeBSD)
    install_pkg gmake gmake
    install_pkg fd fd-find
    install_pkg tree-sitter tree-sitter-cli
    ;;
  esac
}

install_lsp() {
  install_npm basedpyright-langserver basedpyright
  install_npm bash-language-server bash-language-server

  case "$OS" in
  Darwin)
    install_pkg shellcheck shellcheck
    ;;
  FreeBSD)
    install_pkg shellcheck hs-ShellCheck
    ;;
  esac

  install_pkg clangd llvm
  install_npm vscode-html-language-server vscode-langservers-extracted
  install_npm vscode-json-language-server vscode-langservers-extracted
  install_pkg lua-language-server lua-language-server
  install_npm prisma-language-server @prisma/language-server
  install_npm vtsls @vtsls/language-server
}

install_analysis() {
  # sonar-scanner wird direkt von nvim/lua/config/usercmds.lua (:SonarScan)
  # und nvim/scripts/sonarqube.sh (:SonarIssues) genutzt. Nur beruflich
  # unter macOS im Einsatz, deshalb kein FreeBSD-Zweig.
  case "$OS" in
  Darwin)
    install_pkg sonar-scanner sonar-scanner
    ;;
  esac
}

main() {
  check_prerequisites
  setup_homebrew_env

  install_prerequisites
  install_formatters
  install_tools
  install_lsp
  install_analysis

  printf "\nBootstrap abgeschlossen.\n"
}

main "$@"
