#!/usr/bin/env bash
# LLeMbas TERM'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-term-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; a SHA256SUMS that names its product and version (a first line
# `# <product> <version>`) must name the release that was asked for. It refuses to run as root
# (everything goes into your own home); nothing that is already installed is touched (each
# product updates itself: `lembas update`, `llembas-ide update`).
#
# It changes no file of yours. When ~/.zshrc or ~/.bashrc still has the shell integration's line
# from the terminal's earlier name (LLeMbas TTY), it prints the line to put there instead.
#
# 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-term-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_TERM_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_TERM:-}" 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, naming this release
# where it names one, and the installer in it.
checked_installer() { # slug, tag, installer file name, product -> path of the checked file
  local slug="$1" tag="$2" name="$3" product="$4" dir base head
  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"
  # The signature says who made the sums, not which release they are of: a listing that
  # answered with an older signed release under the newest tag would pass it. A first line
  # that names the product and version binds them to the tag asked for.
  head="$(head -n1 "$dir/SHA256SUMS")"
  case "$head" in
    '#'*)
      [ "$head" = "# $product ${tag#v}" ] ||
        die "SHA256SUMS of $slug $tag is of another release (it says: ${head#\# }) — nothing installed"
      ;;
    *) warn "($slug $tag: its SHA256SUMS does not name its release; the signature is checked)" ;;
  esac
  (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 "not installed"
    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 lembas)"
  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 "not installed"
    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 llembas-ide)"
  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"
}

# The terminal was LLeMbas TTY up to 1.0.0-beta.5, and its README gave a line for ~/.zshrc (or
# ~/.bashrc) that sources a file which is no longer there, behind a variable that is no longer
# set: it does nothing now. Say so, with the line that replaces it. The files are only read.
old_rc_line() {
  local rc here file=/usr/share/llembas-term/shell/llembas-term.sh
  here="$(cd "$(dirname "$(readlink -f "$0" 2>/dev/null || printf '%s' "$0")")" 2>/dev/null && pwd)" || here=""
  # unpacked from the tarball: the integration is beside the programs, not under /usr
  if [ -n "$here" ] && [ -r "$here/../../share/llembas-term/shell/llembas-term.sh" ]; then
    file="$(cd "$here/../../share/llembas-term/shell" && pwd)/llembas-term.sh"
  fi
  for rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
    [ -r "$rc" ] || continue
    grep -q 'llembas-tty' "$rc" 2>/dev/null || continue
    say ""
    say "$rc still has the shell integration's line from the terminal's old name (LLeMbas TTY)."
    say "It does nothing any more. Replace it with this one (this program does not change your files):"
    # shellcheck disable=SC2016  # said to the person as they would write it
    say '  [ -n "$LLEMBAS_TERM" ] && . '"$file"
  done
}

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,14p' "$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
  # everything is installed into your own home, and installers are run: never as root
  [ "$(id -u)" != 0 ] || die "run it as yourself, not as root: it installs for your own user only"

  [ "$DRY" = 1 ] || TMP="$(mktemp -d)"

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

  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 "$@"
