#!/usr/bin/env bash
# LLeMbas IDE: the launcher. It starts the IDE's own Neovim with the IDE's own configuration
# (NVIM_APPNAME=llembas-ide), so a Neovim configuration of your own is never read or written.
#
#   llembas-ide [files…]         start the editor; every argument goes to Neovim
#   llembas-ide --version        the versions of the IDE, Neovim and the LLeMbas plugin
#   llembas-ide doctor           check the installation, and say what is off without what
#   llembas-ide update           install the newest release over this one (keeps your settings)
#   llembas-ide uninstall        remove it (--purge: your settings too; --yes: ask nothing)
#
# A file named like one of those words is opened as ./doctor.
set -euo pipefail

PREFIX='' # set by install.sh
APP="llembas-ide"

say() { printf '%s\n' "$*"; }
die() {
  printf 'llembas-ide: %s\n' "$*" >&2
  exit 1
}

[ -n "$PREFIX" ] || die "this launcher was not put in place by the installer (ide/install.sh)"
case "$PREFIX" in /*/*) ;; *) die "the installation's directory ($PREFIX) is not one of the IDE's own" ;; esac
CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}/$APP"
STATE="${XDG_STATE_HOME:-$HOME/.local/state}/$APP"
CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/$APP"
DATA="${XDG_DATA_HOME:-$HOME/.local/share}/$APP"
LIB="$PREFIX/lib"
# Before Neovim is run for anything: its own log and state go to the IDE's directories.
export NVIM_APPNAME="$APP"

recorded() { sed -n "s/^$1=//p" "$LIB/installed" 2>/dev/null | head -n1; }
nvim_path() { cat "$LIB/nvim-path" 2>/dev/null || true; }
sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi
}
has_tty() { [ -r /dev/tty ] && { : </dev/tty; } 2>/dev/null; }
git_quiet() { GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git "$@"; }
lock_lines() { grep -v -E '^[[:space:]]*(#|$)' "$1"; }

# Where the LLeMbas CLI is, or nothing: on PATH, or where its installer puts it. The installer has
# this function word for word, and the plugin the same rule in Lua (require("llembas").cli());
# scripts/test-ide.sh holds the three together.
find_cli() {
  command -v lembas 2>/dev/null && return 0
  [ -x "$HOME/.local/bin/lembas" ] && printf '%s\n' "$HOME/.local/bin/lembas" && return 0
  return 1
}

# What was changed in a plugin's directory since its commit was checked out: files edited or
# deleted, and files added (ignored ones too: Neovim loads whatever lies there). The help tags
# the installer writes itself are not a change.
changed_in() {
  git_quiet -C "$1" status --porcelain --untracked-files=all --ignored 2>/dev/null | grep -v -E '^(\?\?|!!) doc/tags$' || true
}

# Remove a directory only when it is the IDE's own: its last part is the application's name.
remove_app_dir() {
  case "$1" in
    */"$APP") rm -rf -- "$1" ;;
  esac
}

versions() {
  local nvim
  nvim="$(nvim_path)"
  say "LLeMbas IDE     $(cat "$LIB/VERSION" 2>/dev/null || echo unknown)"
  say "Neovim          $("$nvim" --version 2>/dev/null | sed -n '1s/^NVIM v//p' || true)"
  say "LLeMbas plugin  $(cat "$LIB/llembas/VERSION" 2>/dev/null || echo missing)"
}

# --- doctor ------------------------------------------------------------------------------------

BAD=0
WARNED=0
good() { printf '  ok    %s\n' "$*"; }
off() {
  WARNED=$((WARNED + 1))
  printf '  note  %s\n' "$*"
}
bad() {
  BAD=$((BAD + 1))
  printf '  FAIL  %s\n' "$*"
}

doctor() {
  local nvim name where _url commit rest dir count have out lembas paths index
  nvim="$(nvim_path)"
  say "LLeMbas IDE $(cat "$LIB/VERSION" 2>/dev/null || echo '(version unknown)') in $PREFIX"
  say ""
  say "The editor"
  if [ -n "$nvim" ] && "$nvim" --version >/dev/null 2>&1; then
    good "Neovim $("$nvim" --version | sed -n '1s/^NVIM v//p') runs ($nvim; $(cut -d' ' -f1,2 "$LIB/nvim-source" 2>/dev/null))"
  else
    bad "Neovim does not run (${nvim:-no path recorded}); run the installer again"
  fi
  if [ -f "$CONFIG/init.lua" ]; then
    if [ "$(sha256_of "$CONFIG/init.lua")" = "$(recorded init_sha)" ]; then
      good "configuration $CONFIG/init.lua is the IDE's own"
    else
      off "$CONFIG/init.lua was edited; an update keeps yours and writes init.lua.new beside it"
    fi
  else
    bad "$CONFIG/init.lua is missing; run the installer again"
  fi
  if [ -f "$CONFIG/lua/user/init.lua" ]; then
    good "your settings: $CONFIG/lua/user/init.lua"
  else
    off "no settings file of your own ($CONFIG/lua/user/init.lua); the installer creates one"
  fi

  say ""
  say "Plugins, each at its pinned commit"
  if [ ! -f "$LIB/ide/plugins.lock" ]; then
    bad "the list of pinned plugins ($LIB/ide/plugins.lock) is missing; run the installer again"
  elif command -v git >/dev/null 2>&1; then
    while read -r name where _url commit rest; do
      dir="$PREFIX/site/pack/llembas/$where/$name"
      if [ ! -d "$dir/.git" ]; then
        bad "$name is missing"
      elif [ "$(git_quiet -C "$dir" rev-parse HEAD 2>/dev/null)" != "$commit" ]; then
        bad "$name is at $(git_quiet -C "$dir" rev-parse --short HEAD 2>/dev/null), not its pin ${commit:0:12}"
      elif [ -n "$(changed_in "$dir")" ]; then
        bad "$name is at its pin but its files were changed or added to"
      else
        good "$name ${commit:0:12}"
      fi
    done < <(lock_lines "$LIB/ide/plugins.lock")
  else
    off "git is not installed: the plugins' commits cannot be checked, and git signs and diffs are off"
  fi
  if [ -f "$LIB/llembas/nvim/plugin/llembas.lua" ]; then
    good "LLeMbas plugin $(cat "$LIB/llembas/VERSION")"
  else
    bad "the LLeMbas plugin is missing"
  fi
  count="$(lock_lines "$LIB/ide/parsers.lock" 2>/dev/null | wc -l | tr -d ' ' || true)"
  have="$(find "$PREFIX/site/pack/llembas/start/llembas-parsers/parser" -name '*.so' 2>/dev/null | wc -l | tr -d ' ' || true)"
  if [ "$have" = "$count" ] && [ "$count" != 0 ]; then
    good "$have Treesitter grammars compiled"
  else
    off "Treesitter grammars are not compiled: Neovim's bundled ones colour C, Lua, Markdown, Vimscript and help;"
    printf '        %s\n' "other languages use plain syntax files. With a C compiler installed, run: $APP update"
  fi

  say ""
  say "A start, headless"
  if [ -n "$nvim" ]; then
    out="$(NVIM_APPNAME="$APP" LLEMBAS_IDE_PREFIX="$PREFIX" "$nvim" --headless \
      --cmd 'lua vim.g.llembas_ide_no_session = true; vim.g.llembas_ide_no_dashboard = true' \
      -c 'lua local ok, ide = pcall(require, "llembas_ide"); io.stdout:write(ok and ("problems=" .. #ide.problems .. " " .. table.concat(ide.problems, " | ")) or "problems=all the IDE did not load")' \
      -c 'qa!' 2>&1 || true)"
    # As the installer judges the same start: a line of Neovim's own beside it is not a failure.
    case "$out" in
      *"problems=0"*) good "every part of the IDE loads" ;;
      *) bad "the IDE does not start cleanly: ${out#*problems=}" ;;
    esac
  fi

  say ""
  say "Tools the IDE uses when they are there"
  if command -v git >/dev/null 2>&1; then good "git"; else off "git: no git signs, no diff, no update"; fi
  if command -v rg >/dev/null 2>&1; then
    good "rg (ripgrep)"
  else
    off "rg (ripgrep) is missing: searching in files (<Space>/) is off; finding files falls back to git or fd"
  fi
  if command -v fd >/dev/null 2>&1 || command -v fdfind >/dev/null 2>&1; then
    good "fd"
  else
    off "fd is missing: nothing is off, rg or git lists the files"
  fi
  if command -v cc >/dev/null 2>&1 || command -v gcc >/dev/null 2>&1 || command -v clang >/dev/null 2>&1; then
    good "a C compiler"
  else
    off "no C compiler: Treesitter grammars cannot be compiled at install"
  fi
  if command -v curl >/dev/null 2>&1; then good "curl"; else off "curl is missing: $APP update cannot download"; fi
  if command -v ssh-keygen >/dev/null 2>&1; then
    good "ssh-keygen"
  else
    off "ssh-keygen (openssh-client) is missing: $APP update cannot check a release's signature, and stops"
  fi
  if [ -n "${WAYLAND_DISPLAY:-}" ] && ! command -v wl-copy >/dev/null 2>&1; then
    off "wl-clipboard is missing: the system clipboard is off"
  fi
  if [ -z "${WAYLAND_DISPLAY:-}" ] && [ -n "${DISPLAY:-}" ] && ! command -v xclip >/dev/null 2>&1 && ! command -v xsel >/dev/null 2>&1; then
    off "xclip or xsel is missing: the system clipboard is off"
  fi
  case ":$PATH:" in *":$(dirname "$0"):"*) ;; *) off "$(dirname "$0") is not on your PATH" ;; esac

  say ""
  say "LLeMbas"
  lembas="$(find_cli || true)"
  if [ -z "$lembas" ]; then
    off "the LLeMbas CLI (lembas) is not installed: chat, asking, rewriting and suggestions are off; the editor works. https://github.com/LLeMbas/LLeMbas-CLI"
  else
    good "LLeMbas CLI $("$lembas" --version 2>/dev/null || echo '(no version)') ($lembas)"
    command -v lembas >/dev/null 2>&1 || off "$(dirname "$lembas") is not on your PATH: the IDE finds the CLI there all the same; a terminal does not"
    # Where the CLI keeps its sign-ins; it has no command that only says whether there is one.
    paths="$("$lembas" __paths 2>/dev/null || true)"
    index="$(printf '%s\n' "$paths" | sed -n 's/^config=//p')/lembas.json"
    if [ -z "$paths" ]; then
      off "could not tell whether the CLI is signed in; try: lembas login <your server's address>"
    elif [ -f "$index" ] && grep -q '"base_url"' "$index"; then
      good "signed in to a LLeMbas server"
    else
      off "not signed in: lembas login <your server's address>"
    fi
  fi

  say ""
  if [ "$BAD" -gt 0 ]; then
    if [ "$BAD" = 1 ]; then say "1 check failed. $APP update installs it again."; else say "$BAD checks failed. $APP update installs it again."; fi
    return 1
  fi
  if [ "$WARNED" -gt 0 ]; then
    if [ "$WARNED" = 1 ]; then say "The installation is sound; the note above says what is off."; else say "The installation is sound; the $WARNED notes above say what is off."; fi
  else
    say "The installation is sound."
  fi
}

# --- update ------------------------------------------------------------------------------------

update() {
  local channel=stable args=()
  [ -f "$LIB/ide/install.sh" ] || die "the installer is missing from $LIB; install again from https://github.com/LLeMbas/LLeMbas-IDE"
  # A beta stays with the betas, a release with the releases; --channel says otherwise.
  case "$(cat "$LIB/VERSION" 2>/dev/null)" in *-beta.*) channel=beta ;; esac
  args=(--prefix "$PREFIX" --channel "$channel")
  case "$(cat "$LIB/nvim-source" 2>/dev/null)" in own\ *) args+=(--nvim-bin "$(nvim_path)") ;; esac
  # Left out on purpose at install, the grammars stay out.
  [ "$(recorded parsers)" != off ] || args+=(--no-parsers)
  # The installed installer finds the newest release, checks it, and runs the installer inside it.
  exec bash "$LIB/ide/install.sh" "${args[@]}" "$@"
}

# --- uninstall ---------------------------------------------------------------------------------

uninstall() {
  local purge=0 yes=0 a answer launcher desktop icon keep_config=1
  for a in "$@"; do
    case "$a" in
      --purge) purge=1 ;;
      --yes | -y) yes=1 ;;
      *) die "uninstall takes --purge and --yes" ;;
    esac
  done
  launcher="$(recorded launcher)"
  desktop="$(recorded desktop)"
  icon="$(recorded icon)"
  [ -n "$launcher" ] || launcher="$0"
  say "This removes LLeMbas IDE:"
  say "  $PREFIX/nvim, $PREFIX/site/pack/llembas, $PREFIX/lib"
  say "  $launcher${desktop:+, $desktop, $icon}"
  say "  its history and cache ($STATE, $CACHE)"
  if [ "$purge" = 1 ]; then say "  and your own settings: $CONFIG"; else say "Your own settings in $CONFIG are kept."; fi
  say "Nothing else is touched: not ~/.config/nvim, not the LLeMbas CLI."
  if [ "$yes" != 1 ]; then
    has_tty || die "no terminal to ask on; add --yes"
    printf 'Remove it? [y/N] ' >/dev/tty
    read -r answer </dev/tty || answer=""
    case "$answer" in y | Y | yes | Yes) ;; *) say "Nothing removed." && return 0 ;; esac
    if [ "$purge" != 1 ] && [ -d "$CONFIG" ]; then
      printf 'Remove your own settings in %s too? [y/N] ' "$CONFIG" >/dev/tty
      read -r answer </dev/tty || answer=""
      case "$answer" in y | Y | yes | Yes) keep_config=0 ;; esac
    fi
  fi
  [ "$purge" != 1 ] || keep_config=0

  # The configuration: the IDE's own init.lua goes when it is still the IDE's; what you wrote stays.
  if [ "$keep_config" = 0 ]; then
    remove_app_dir "$CONFIG"
  else
    if [ -f "$CONFIG/init.lua" ] && [ "$(sha256_of "$CONFIG/init.lua")" = "$(recorded init_sha)" ]; then
      rm -f -- "$CONFIG/init.lua"
    fi
    rm -f -- "$CONFIG/init.lua.new"
  fi
  [ -z "$desktop" ] || rm -f -- "$desktop"
  [ -z "$icon" ] || rm -f -- "$icon"
  remove_app_dir "$STATE"
  remove_app_dir "$CACHE"
  rm -rf -- "${PREFIX:?}/nvim" "${PREFIX:?}/site/pack/llembas" "${PREFIX:?}/lib"
  find "${PREFIX:?}" -maxdepth 1 \( -name '.staging.*' -o -name '.old.*' \) -exec rm -rf -- {} + 2>/dev/null || true
  rmdir "$PREFIX/site/pack" "$PREFIX/site" 2>/dev/null || true
  # What Neovim itself left in its data directory goes with a purge; otherwise only if empty.
  [ "$purge" != 1 ] || remove_app_dir "$DATA"
  rmdir "$PREFIX" 2>/dev/null || true
  rmdir "$DATA" 2>/dev/null || true
  rm -f -- "$launcher"
  if [ "$keep_config" = 1 ] && [ -d "$CONFIG" ]; then
    say "LLeMbas IDE is removed. Your settings are still in $CONFIG."
  else
    say "LLeMbas IDE is removed."
  fi
}

case "${1:-}" in
  --version | -V)
    versions
    exit 0
    ;;
  doctor)
    doctor
    exit $?
    ;;
  update)
    shift
    update "$@"
    ;;
  uninstall)
    shift
    uninstall "$@"
    exit 0
    ;;
  --launcher-help)
    sed -n '2,/^set -euo/p' "$0" | sed -e '$d' -e 's/^# \{0,1\}//'
    exit 0
    ;;
esac

NVIM="$(nvim_path)"
if [ -z "$NVIM" ] || [ ! -x "$NVIM" ]; then
  die "the IDE's Neovim is missing (${NVIM:-no path recorded}); run the installer again"
fi
export NVIM_APPNAME="$APP" LLEMBAS_IDE_PREFIX="$PREFIX" LLEMBAS_IDE_LAUNCHER="$0"
exec "$NVIM" "$@"
