#!/usr/bin/env bash
# LLeMbas TTY's set-up: install what is missing of the LLeMbas family beside the terminal —
# the LLeMbas CLI (`lembas`) and LLeMbas IDE (`llembas-ide`) — each as its own installation,
# the same one you use outside this terminal. The terminal carries no copy of either.
#
#   llembas-tty-setup [--yes] [--dry-run] [--channel stable|beta] [--no-cli] [--no-ide]
#
# For each one that is not installed it says what it would do and asks. What it then runs is
# that product's own installer, from that product's own release, and only after checking it:
# the release's SHA256SUMS must be signed with the LLeMbas release key, and the installer must
# match SHA256SUMS. Nothing runs as root; nothing that is already installed is touched (each
# product updates itself: `lembas update`, `llembas-ide update`).
#
# Environment (for a mirror or a build of your own):
#   LLEMBAS_SETUP_FORGE    where the releases are (default https://github.com)
#   LLEMBAS_SETUP_API      its releases API (default https://api.github.com)
#   LLEMBAS_SETUP_PUBKEY   the ssh-ed25519 key SHA256SUMS.sig must be signed with
set -euo pipefail

FORGE="${LLEMBAS_SETUP_FORGE:-https://github.com}"
API="${LLEMBAS_SETUP_API:-https://api.github.com}"
PUBKEY="${LLEMBAS_SETUP_PUBKEY:-ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa}"
NAMESPACE=lembas-release
CLI_SLUG=LLeMbas/LLeMbas-CLI
IDE_SLUG=LLeMbas/LLeMbas-IDE

YES=0
DRY=0
WANT_CLI=1
WANT_IDE=1
CHANNEL=""
TMP=""

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

cleanup() {
  local status=$?
  trap - EXIT
  [ -z "$TMP" ] || rm -rf "$TMP"
  exit "$status"
}

# Started by the terminal in a pane of its own, the pane closes with this program: wait for a
# key first, so that what was said can be read.
pause() {
  [ -n "${LLEMBAS_TTY_PANE:-}" ] && [ "$YES" != 1 ] && [ -r /dev/tty ] || return 0
  printf '\nPress Enter to close. ' >/dev/tty
  read -r _ </dev/tty || true
}

# The channel of this terminal unless one was named: a beta terminal installs betas.
channel() {
  if [ -n "$CHANNEL" ]; then
    printf '%s' "$CHANNEL"
    return
  fi
  case "${LLEMBAS_TTY:-}" in *-*) printf beta ;; *) printf stable ;; esac
}

# A program on PATH, or where both installers put theirs.
have() {
  command -v "$1" 2>/dev/null && return 0
  [ -x "$HOME/.local/bin/$1" ] && printf '%s\n' "$HOME/.local/bin/$1" && return 0
  return 1
}

ask() { # question; answers yes with --yes, no where nobody can answer
  [ "$YES" = 1 ] && return 0
  [ -r /dev/tty ] || return 1
  local answer
  printf '%s [Y/n] ' "$1" >/dev/tty
  read -r answer </dev/tty || return 1
  case "$answer" in "" | y | Y | yes | Yes) return 0 ;; *) return 1 ;; esac
}

fetch() { # url, file — https only, or a file on this machine
  case "$1" in
    https://* | file:///*) ;;
    *) die "refusing to download $1: only https:// (or a local file://) is used" ;;
  esac
  curl -fsSL --retry 2 --proto '=https,file' --proto-redir '=https' -o "$2" "$1"
}

# The newest release tag of a repository on a channel: vX.Y.Z, and on beta also vX.Y.Z-beta.N.
newest() { # slug, channel
  local slug="$1" chan="$2" list="$TMP/releases.json" tag url
  url="$API/repos/$slug/releases"
  # A listing kept as a file (a mirror on this machine) has no query to answer.
  case "$API" in file://*) ;; *) url="$url?per_page=50" ;; esac
  fetch "$url" "$list" 2>/dev/null || return 1
  # One "tag_name" a release, newest first; a draft has none that is published.
  while IFS= read -r tag; do
    case "$chan" in
      beta) [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$ ]] && printf '%s' "$tag" && return 0 ;;
      *) [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] && printf '%s' "$tag" && return 0 ;;
    esac
  done < <(grep -o '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' "$list" | sed -E 's/.*"([^"]*)"$/\1/')
  return 1
}

# A release's installer, checked: SHA256SUMS signed by the release key, the installer in it.
checked_installer() { # slug, tag, installer file name -> path of the checked file
  local slug="$1" tag="$2" name="$3" dir base
  dir="$TMP/$(printf '%s' "$slug-$tag" | tr '/' '-')"
  base="$FORGE/$slug/releases/download/$tag"
  mkdir -p "$dir"
  command -v ssh-keygen >/dev/null 2>&1 || die "needs ssh-keygen (openssh-client): it checks the release's signature"
  command -v sha256sum >/dev/null 2>&1 || die "needs sha256sum: it checks what was downloaded"
  fetch "$base/SHA256SUMS" "$dir/SHA256SUMS" || die "could not download SHA256SUMS of $slug $tag — nothing installed"
  fetch "$base/SHA256SUMS.sig" "$dir/SHA256SUMS.sig" 2>/dev/null || die "$slug $tag is not signed (no SHA256SUMS.sig) — nothing installed"
  fetch "$base/$name" "$dir/$name" || die "could not download $name of $slug $tag — nothing installed"
  printf '%s %s\n' "$NAMESPACE" "$PUBKEY" >"$dir/allowed"
  ssh-keygen -Y verify -f "$dir/allowed" -I "$NAMESPACE" -n "$NAMESPACE" -s "$dir/SHA256SUMS.sig" <"$dir/SHA256SUMS" >/dev/null 2>&1 ||
    die "SHA256SUMS of $slug $tag is not signed by the LLeMbas release key — nothing installed"
  (cd "$dir" && grep -E "^[0-9a-f]{64}  \*?$name\$" SHA256SUMS | sed 's/  \*/  /' | sha256sum -c --strict --quiet - >/dev/null 2>&1) ||
    die "$name of $slug $tag does not match its SHA256SUMS — nothing installed"
  printf '%s' "$dir/$name"
}

setup_cli() {
  local at tag chan installer
  if at="$(have lembas)"; then
    note "the LLeMbas CLI is installed: $at ($("$at" --version 2>/dev/null | head -n1 || echo "version unknown"))"
    return 0
  fi
  chan="$(channel)"
  say "The LLeMbas CLI (lembas) is not installed."
  if [ "$DRY" = 1 ]; then
    note "would find the newest $chan release of $CLI_SLUG, check its get.sh against the release key, and run it"
    note "it installs for this user only, into ~/.local/bin and ~/.local/share/lembas"
    return 0
  fi
  ask "Install it now, for this user only?" || {
    note "left out"
    return 0
  }
  tag="$(newest "$CLI_SLUG" "$chan")" || die "no $chan release of $CLI_SLUG was found (is this machine online?) — nothing installed"
  installer="$(checked_installer "$CLI_SLUG" "$tag" get.sh)"
  note "LLeMbas CLI $tag: signature good, installing"
  LEMBAS_REF="$tag" LEMBAS_CHANNEL="$chan" bash "$installer" || die "the LLeMbas CLI's installer stopped — see above"
}

setup_ide() {
  local at tag chan installer
  if at="$(have llembas-ide)"; then
    note "LLeMbas IDE is installed: $at"
    return 0
  fi
  chan="$(channel)"
  say "LLeMbas IDE (llembas-ide, the editor) is not installed."
  if [ "$DRY" = 1 ]; then
    note "would find the newest $chan release of $IDE_SLUG, check its install.sh against the release key, and run it"
    note "it installs for this user only, under its own name: your own Neovim is not touched"
    return 0
  fi
  ask "Install it now, for this user only?" || {
    note "left out"
    return 0
  }
  tag="$(newest "$IDE_SLUG" "$chan")" || die "no $chan release of $IDE_SLUG was found (is this machine online?) — nothing installed"
  installer="$(checked_installer "$IDE_SLUG" "$tag" install.sh)"
  note "LLeMbas IDE $tag: signature good, installing"
  # --no-cli: the CLI is this program's own step above.
  bash "$installer" --version "${tag#v}" --channel "$chan" --no-cli --yes || die "LLeMbas IDE's installer stopped — see above"
}

main() {
  trap cleanup EXIT
  while [ $# -gt 0 ]; do
    case "$1" in
      --yes) YES=1 ;;
      --dry-run) DRY=1 ;;
      --no-cli) WANT_CLI=0 ;;
      --no-ide) WANT_IDE=0 ;;
      --channel)
        CHANNEL="${2:?--channel needs stable or beta}"
        shift
        ;;
      -h | --help)
        sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//'
        return 0
        ;;
      *) die "unknown option $1 (see --help)" ;;
    esac
    shift
  done
  case "$(channel)" in stable | beta) ;; *) die "--channel is stable or beta" ;; esac
  [ "$DRY" = 1 ] || TMP="$(mktemp -d)"

  say "LLeMbas TTY set-up ($(channel) releases)"
  [ "$WANT_CLI" != 1 ] || setup_cli
  [ "$WANT_IDE" != 1 ] || setup_ide

  if [ "$DRY" != 1 ]; then
    say ""
    if have lembas >/dev/null; then
      say "To use LLeMbas, log in to your server once:  lembas login <address of your server>"
      say "(or the command palette entry \"LLeMbas: log in\")."
    fi
    # shellcheck disable=SC2088,SC2016  # said to the person as they would type it
    case ":$PATH:" in
      *":$HOME/.local/bin:"*) ;;
      *) [ ! -d "$HOME/.local/bin" ] || say '~/.local/bin is not on your PATH: the terminal finds both programs there anyway; for your shell add  export PATH="$HOME/.local/bin:$PATH"' ;;
    esac
  fi
  pause
}

main "$@"
