#!/bin/sh
# muster.tools installer. GENERATED by templates/install/render.sh from
# templates/install/sites/muster.tools.conf + templates/install/core.sh.
# Do not edit this file: edit those, then run templates/install/render.sh.
#
#   curl -fsSL https://muster.tools/install.sh | sh

# ---- site settings --------------------------------------------------------
LABEL=muster
DOMAIN=muster.tools
PREFIX=MUSTER
DEFAULT_DIR="$HOME/.local/bin"
SYSTEM_DIR=0
TOOLS="muster"
SELECTABLE=0
# muster-deploy stands up the optional hosted backend in your own AWS account.
# It links the AWS SDK the muster binary deliberately omits, so it is opt-in.
# Its smoke test is -version: its job is to create real AWS infrastructure,
# and a smoke test must never be able to start one.
EXTRA="muster-deploy:--with-deploy:muster"
GATED=1
SMOKE_MUSTER_DEPLOY="-version"
NEXT="next: finish setting up as https://subaud.tools/llms.txt says under After install, then tell the person to say: Get me started with subaud."
EXTRA_HINT="one bus across several machines? re-run with --with-deploy for the hosted backend installer"

# ---- install core (templates/install/core.sh) --------------------------------
# One installer for every .tools site. render.sh prepends a site's settings
# (templates/install/sites/<domain>.conf) and writes sites/<domain>/install.sh.
# Edit this file or a .conf and re-render; never edit a generated install.sh.
#
# Settings a .conf provides:
#   LABEL         name used in messages ("kempt")
#   DOMAIN        site domain ("kempt.tools")
#   PREFIX        env var prefix: <PREFIX>_DL_HOST, <PREFIX>_INSTALL_DIR
#   DEFAULT_DIR   install directory when <PREFIX>_INSTALL_DIR is unset
#   SYSTEM_DIR    1 = DEFAULT_DIR is a system directory: use sudo only when it
#                 is not writable (galley); 0 = create it (~/.local/bin)
#   TOOLS         tools this site installs, each served at /dl/<tool>/
#   SELECTABLE    1 = positional args choose among TOOLS (tackle); 0 = none
#   EXTRA         optional extra binary "<name>:<flag>:<tool>": installed only
#                 with <flag>, from <tool>'s release (muster-deploy)
#   SMOKE_<name>  argument that runs a binary without side effects (default
#                 "version"); '-' in <name> becomes '_'
#   NEXT          line printed when done
#   EXTRA_HINT    line printed when EXTRA exists but was not asked for
#   GATED         1 = downloads need a machine signed in to subaud.tools: every
#                 file is fetched through a signed link from the access service
#                 (<PREFIX>_API_HOST, default https://api.subaud.tools)
#   PRODUCT       what a gated site's links are asked for, when one product
#                 covers every tool here (tackle); default each tool's name
#
# The family download contract:
#   https://<DOMAIN>/dl/<tool>/<version>/<tool>_<os>_<arch>.tar.gz(.sha256)
#   https://<DOMAIN>/dl/<tool>/latest   (plain-text bare semver)
# Pin a version with <TOOL>_VERSION=X.Y.Z (a leading v is stripped). Every
# download is verified against its .sha256 sidecar FAIL-CLOSED before it is
# unpacked, and every installed binary is run once before success is reported.
#
# A gated site's machine token is $SUBAUD_TOKEN, else the token file in the
# subaud config directory (an absolute $SUBAUD_HOME/config, else an absolute
# $XDG_CONFIG_HOME/subaud, else ~/.config/subaud), as every tool reads it.
# With neither, or when the access service refuses the token, it prints the
# line that points to the account page (Set up a machine), whose setup
# line signs the machine in, and exits 1.
# The token never reaches the output or a command line.
set -eu

# shellcheck disable=SC2018,SC2019  # ASCII names; '-' must map to '_'
upper() { printf '%s' "$1" | tr 'a-z-' 'A-Z_'; }
fail() { printf '%s install: %s\n' "$LABEL" "$*" >&2; exit 1; }
getvar() { eval "printf '%s' \"\${$1:-}\""; }

host="$(getvar "${PREFIX}_DL_HOST")"; host="${host:-https://$DOMAIN}"
install_dir="$(getvar "${PREFIX}_INSTALL_DIR")"; install_dir="${install_dir:-$DEFAULT_DIR}"

extra_name=""; extra_flag=""; extra_tool=""; want_extra=0
if [ -n "${EXTRA:-}" ]; then
  extra_name="${EXTRA%%:*}"; rest="${EXTRA#*:}"; extra_flag="${rest%%:*}"; extra_tool="${rest#*:}"
fi

usage() {
  if [ "$SELECTABLE" = 1 ]; then
    printf 'usage: install.sh [tool ...]   (default: all of: %s)\n' "$TOOLS"
    printf '  <TOOL>_VERSION=X.Y.Z pins an exact version (e.g. %s_VERSION).\n' "$(upper "${TOOLS%% *}")"
  else
    printf 'usage: install.sh%s\n' "${extra_flag:+ [$extra_flag]}"
    printf '  %s_VERSION=X.Y.Z pins an exact version.\n' "$(upper "${TOOLS%% *}")"
    [ -z "$extra_flag" ] || printf '  %s  also install %s\n' "$extra_flag" "$extra_name"
  fi
  printf '  %s_INSTALL_DIR overrides the install directory (default %s).\n' "$PREFIX" "$DEFAULT_DIR"
}

chosen=""
for arg in "$@"; do
  case "$arg" in
    -h|--help) usage; exit 0 ;;
    -*)
      if [ -n "$extra_flag" ] && [ "$arg" = "$extra_flag" ]; then want_extra=1
      else fail "unknown option '$arg' (see --help)"; fi ;;
    *)
      [ "$SELECTABLE" = 1 ] || fail "unexpected argument '$arg' (see --help)"
      ok=0; for t in $TOOLS; do [ "$arg" = "$t" ] && ok=1; done
      [ "$ok" = 1 ] || fail "unknown tool '$arg' (known: $TOOLS)"
      chosen="$chosen $arg" ;;
  esac
done
[ -n "$chosen" ] || chosen="$TOOLS"

command -v curl >/dev/null 2>&1 || fail "curl is required"
command -v tar  >/dev/null 2>&1 || fail "tar is required"

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$os" in
  darwin|linux) ;;
  *) fail "unsupported OS '$os': $LABEL runs on macOS and Linux (on Windows, install inside WSL2)" ;;
esac
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64)  arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) fail "unsupported architecture '$arch' (need amd64 or arm64)" ;;
esac

if command -v shasum >/dev/null 2>&1; then sha256_of() { shasum -a 256 "$1" | cut -d' ' -f1; }
elif command -v sha256sum >/dev/null 2>&1; then sha256_of() { sha256sum "$1" | cut -d' ' -f1; }
else fail "neither shasum nor sha256sum is available; refusing to install an unverified binary"; fi

tmp="$(mktemp -d)" || fail "could not create a temporary directory"
trap 'rm -rf "$tmp"' EXIT INT TERM

# ---- signing in (gated sites) -------------------------------------------------
api="$(getvar "${PREFIX}_API_HOST")"; api="${api:-https://api.subaud.tools}"
case "${SUBAUD_HOME:-}" in
  /*) cfg="$SUBAUD_HOME/config" ;;
  *) case "${XDG_CONFIG_HOME:-}" in /*) cfg="$XDG_CONFIG_HOME/subaud" ;; *) cfg="$HOME/.config/subaud" ;; esac ;;
esac
account_page="https://subaud.tools/account/"
signed_out="This machine isn't signed in to subaud.tools. Get your setup line at ${account_page} (Set up a machine) and paste it in a terminal on this machine."

# json_field <name>: a string field of the JSON on stdin, without jq. Go's
# encoder writes & < > as \u0026 \u003c \u003e, so those are turned back.
json_field() {
  tr -d '\n' | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" |
    sed 's/\\u0026/\&/g; s/\\u003c/</g; s/\\u003e/>/g'
}

# post <route> [token]: POST $tmp/body to the access service; the answer goes
# to $tmp/resp and its status code to stdout. The token goes through a curl
# config file, so it never appears on a command line.
post() {
  umask 077 # post runs in its own subshell: the token, body and answer files stay private
  if [ -n "${2:-}" ]; then
    printf 'header = "Authorization: Bearer %s"\n' "$2" > "$tmp/auth"
  else
    : > "$tmp/auth"
  fi
  curl -sS -o "$tmp/resp" -w '%{http_code}' -K "$tmp/auth" -H 'Content-Type: application/json' \
    --data-binary @"$tmp/body" "$api$1" || fail "could not reach the access service at $api"
}

# not_signed_in: the machine has no token the access service accepts.
not_signed_in() { printf '%s\n' "$signed_out" >&2; exit 1; }

# fetch_signed <url> [out]: GET a signed link through a private curl config,
# so its signature never appears on a command line; to stdout without out.
fetch_signed() {
  (umask 077 && printf 'url = "%s"\n' "$(printf '%s' "$1" | sed 's/[\\"]/\\&/g')" > "$tmp/get") || return 1
  if [ -n "${2:-}" ]; then curl -fsSL -K "$tmp/get" -o "$2"; else curl -fsSL -K "$tmp/get"; fi
}

# sign_in: sets token from $SUBAUD_TOKEN or the token file; with neither, it
# points to the account page's line.
sign_in() {
  token="${SUBAUD_TOKEN:-}"
  if [ -z "$token" ] && [ -f "$cfg/token" ]; then token="$(tr -d ' \t\r\n' < "$cfg/token")"; fi
  [ -n "$token" ] || not_signed_in
}

# link <tool> <path>: a five-minute signed URL for /dl/<path>, asked with the
# token for the product PRODUCT, else <tool>.
link() {
  printf '{"product":"%s","path":"%s"}' "${PRODUCT:-$1}" "$2" > "$tmp/body"
  code="$(post /links "$token")" || exit 1
  case "$code" in
    200) u="$(json_field url < "$tmp/resp")"; [ -n "$u" ] || fail "the access service sent no link for $2"; printf '%s' "$u" ;;
    401) not_signed_in ;;
    403) a="$(json_field account < "$tmp/resp")"; fail "this account does not own ${PRODUCT:-$1}: get it at ${a:-$account_page}" ;;
    *) fail "could not get a download link for $2 (the access service answered $code)" ;;
  esac
}

[ "${GATED:-0}" != 1 ] || sign_in

# version_for <tool>: the <TOOL>_VERSION pin, else the latest pointer.
version_for() {
  v="$(getvar "$(upper "$1")_VERSION")"
  if [ -z "$v" ] && [ "${GATED:-0}" = 1 ]; then
    u="$(link "$1" "$1/latest")" || exit 1
    v="$(fetch_signed "$u")" || fail "could not read the latest pointer for $1 from $DOMAIN"
    v="$(printf '%s' "$v" | tr -d ' \t\r\n')"
    [ -n "$v" ] || fail "the latest pointer for $1 was empty"
  elif [ -z "$v" ]; then
    v="$(curl -fsSL "$host/dl/$1/latest")" || fail "could not read the latest pointer at $host/dl/$1/latest"
    v="$(printf '%s' "$v" | tr -d ' \t\r\n')"
    [ -n "$v" ] || fail "the latest pointer for $1 was empty"
  fi
  printf '%s' "${v#v}"
}

# place <file> <name>: into install_dir, with sudo only for a system
# directory that is not writable.
place() {
  if [ "$SYSTEM_DIR" = 1 ]; then
    if [ -d "$install_dir" ] && [ -w "$install_dir" ]; then
      mv "$1" "$install_dir/$2"
    elif command -v sudo >/dev/null 2>&1; then
      printf '%s: installing to %s (sudo)\n' "$LABEL" "$install_dir"
      # shellcheck disable=SC2015  # fail if any of the three steps fails
      sudo mkdir -p "$install_dir" && sudo mv "$1" "$install_dir/$2" && sudo chmod 755 "$install_dir/$2" \
        || fail "could not install to $install_dir with sudo"
    else
      fail "$install_dir is not writable and sudo is unavailable; re-run with ${PREFIX}_INSTALL_DIR set to a directory on your PATH"
    fi
  else
    # shellcheck disable=SC2015  # fail if either step fails
    mkdir -p "$install_dir" && mv "$1" "$install_dir/$2" || fail "could not install to $install_dir"
  fi
}

# fetch <binary> <version> <tool>: download <tool>'s asset for <binary>,
# verify it, install it, and run it once.
fetch() {
  name="$1"; version="$2"; tool="$3"
  asset="${name}_${os}_${arch}.tar.gz"
  if [ "${GATED:-0}" = 1 ]; then
    url="https://$DOMAIN/dl/$tool/$version/$asset" # shown; the signed links are not
    src="$(link "$tool" "$tool/$version/$asset")" || exit 1
    sum_src="$(link "$tool" "$tool/$version/$asset.sha256")" || exit 1
  else
    url="$host/dl/$tool/$version/$asset"; src="$url"; sum_src="$url.sha256"
  fi
  printf 'downloading %s (%s) …\n' "$asset" "$version"
  if [ "${GATED:-0}" = 1 ]; then
    fetch_signed "$src" "$tmp/$asset" || fail "download failed: $url"
    fetch_signed "$sum_src" "$tmp/$asset.sha256" || fail "could not fetch the checksum for $asset; refusing to install an unverified binary"
  else
    curl -fsSL "$src"     -o "$tmp/$asset"        || fail "download failed: $url"
    curl -fsSL "$sum_src" -o "$tmp/$asset.sha256" || fail "could not fetch the checksum for $asset; refusing to install an unverified binary"
  fi
  expected="$(cut -d' ' -f1 < "$tmp/$asset.sha256")"
  [ -n "$expected" ] || fail "empty checksum for $asset"
  actual="$(sha256_of "$tmp/$asset")"
  [ "$actual" = "$expected" ] || fail "checksum mismatch for $asset (expected $expected, got $actual): the download is corrupt or was tampered with; nothing was installed"
  mkdir -p "$tmp/x"
  tar -xzf "$tmp/$asset" -C "$tmp/x" || fail "could not unpack $asset"
  [ -f "$tmp/x/$name" ] || fail "$asset did not contain a $name binary"
  chmod 755 "$tmp/x/$name"
  place "$tmp/x/$name" "$name"
  smoke="$(getvar "SMOKE_$(upper "$name")")"; smoke="${smoke:-version}"
  out="$("$install_dir/$name" "$smoke" 2>&1)" || fail "the installed $name failed to run ($install_dir/$name $smoke)"
  printf 'installed %s to %s\n' "$(printf '%s\n' "$out" | head -1)" "$install_dir/$name"
}

for t in $chosen; do v="$(version_for "$t")" || exit 1; fetch "$t" "$v" "$t"; done
if [ "$want_extra" = 1 ]; then v="$(version_for "$extra_tool")" || exit 1; fetch "$extra_name" "$v" "$extra_tool"; fi

# shellcheck disable=SC2016  # $PATH is printed literally, for the user to paste
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *) printf 'note: %s is not on your PATH; add:  export PATH="%s:$PATH"\n' "$install_dir" "$install_dir" ;;
esac
[ -z "${NEXT:-}" ] || printf '%s\n' "$NEXT"
if [ -n "${EXTRA_HINT:-}" ] && [ "$want_extra" = 0 ]; then printf '%s\n' "$EXTRA_HINT"; fi
