#!/bin/sh
# Installs zerohead for your user on Linux x86_64:
#
#   curl -fsSL https://zerohead.app/install.sh | sh
#
# What it does, from top to bottom:
#   1. Checks that this is Linux on x86_64, and changes nothing if it is not.
#   2. Reads which release is the latest from the download address below.
#   3. Downloads that release and checks its SHA-256. On a mismatch it stops and installs nothing.
#   4. Puts the program in ~/.local/bin (or $ZEROHEAD_INSTALL_DIR), after checking that it runs.
#   5. Runs `zerohead service install`, which starts zerohead in the background as your own
#      service and prints its address and a link to pair your browser.
#
# It needs no sudo, and sends nothing anywhere except the download requests (https only). Run it
# again to update to the latest release; the service restarts with it and keeps its data folder
# and port.
#
# To remove the program and the service (your data is kept):
#
#   curl -fsSL https://zerohead.app/install.sh | sh -s -- --uninstall
#
# The whole script is one block in braces: the shell reads it to the closing brace before it runs
# anything, so a download cut short runs nothing.
{

DOWNLOAD_URL="${ZEROHEAD_DOWNLOAD_URL:-https://zerohead.app/download}"

main() {
  set -eu
  install_dir="${ZEROHEAD_INSTALL_DIR:-$HOME/.local/bin}"
  case "${1:-}" in
    "") ;;
    --uninstall)
      uninstall
      return
      ;;
    *)
      say "Unknown option: $1. The only option is --uninstall."
      exit 2
      ;;
  esac

  # 1. This system.
  os="$(uname -s)"
  arch="$(uname -m)"
  if [ "$os" != Linux ] || [ "$arch" != x86_64 ]; then
    say "zerohead installs on Linux x86_64 today (this is $os on $arch); macOS, Windows and other processors are coming."
    exit 1
  fi
  if [ "$(id -u)" = 0 ]; then
    say "This installs zerohead for the root user; it needs no sudo, so run it as your own user to install it for yourself."
  fi

  # Everything temporary goes, however the script ends (dash runs the EXIT trap only on a
  # normal exit, hence the signals).
  tmp="$(mktemp -d)"
  trap cleanup EXIT
  trap 'cleanup; exit 130' INT TERM HUP

  # 2. The latest release: lines of version=, file= and sha256=.
  fetch "$DOWNLOAD_URL/latest/linux-x86_64" "$tmp/latest"
  version="$(sed -n 's/^version=//p' "$tmp/latest")"
  file="$(sed -n 's/^file=//p' "$tmp/latest")"
  expected="$(sed -n 's/^sha256=//p' "$tmp/latest")"
  case "$version" in
    "" | *[!0-9A-Za-z.+-]*) fail "The list of releases at $DOWNLOAD_URL could not be read." ;;
  esac
  [ "$file" = "zerohead-$version-linux-x86_64.tar.gz" ] || fail "The list of releases at $DOWNLOAD_URL could not be read."
  case "$expected" in
    "" | *[!0-9a-f]*) fail "The list of releases at $DOWNLOAD_URL has no valid SHA-256." ;;
  esac

  # 3. The release, checked.
  say "Downloading zerohead $version..."
  fetch "$DOWNLOAD_URL/releases/$version/$file" "$tmp/$file"
  actual="$(sha256 "$tmp/$file")"
  if [ "$actual" != "$expected" ]; then
    fail "The download's SHA-256 does not match the published one, so nothing was installed. Try again later."
  fi
  tar -xzf "$tmp/$file" -C "$tmp"
  program="$tmp/${file%.tar.gz}/zerohead"
  [ -f "$program" ] || fail "The release has no zerohead program in it, so nothing was installed."

  # 4. The program: copied beside the old one, checked there (a temporary folder may not allow
  # running programs), then renamed over it in one step, even while the old one runs.
  mkdir -p "$install_dir"
  new="$install_dir/.zerohead.new"
  cp "$program" "$new"
  chmod 755 "$new"
  if ! "$new" --version >/dev/null 2>&1 </dev/null; then
    rm -f "$new"
    fail "zerohead $version does not run on this computer, so nothing was installed."
  fi
  mv -f "$new" "$install_dir/zerohead"
  new=""
  say "Installed zerohead $version as $install_dir/zerohead."
  case ":${PATH:-}:" in
    *":$install_dir:"*) ;;
    *)
      case "${SHELL:-}" in
        */zsh) profile="~/.zshrc" ;;
        */bash) profile="~/.bashrc" ;;
        *) profile="~/.profile" ;;
      esac
      say ""
      say "$install_dir is not on your PATH, so typing zerohead does not find it yet. To add it:"
      say ""
      say "  echo 'export PATH=\"$install_dir:\$PATH\"' >> $profile"
      say ""
      say "then open a new terminal."
      ;;
  esac
  say ""

  # 5. The service. It keeps the data folder and port it had, and prints the address and the
  # pairing link.
  if ! "$install_dir/zerohead" service install </dev/null; then
    say ""
    fail "zerohead is installed, but its service did not start (see above). You can start it yourself with: $install_dir/zerohead serve"
  fi
}

uninstall() {
  program="$install_dir/zerohead"
  if [ ! -e "$program" ]; then
    unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/${ZEROHEAD_SERVICE_NAME:-zerohead}.service"
    if [ -e "$unit" ]; then
      say "The zerohead program is gone from $install_dir, but its service is still installed ($unit). Remove the service with:"
      say ""
      say "  systemctl --user disable --now ${ZEROHEAD_SERVICE_NAME:-zerohead}.service"
      say "  rm '$unit'"
      say ""
      say "Your data folder is left as it is."
      exit 1
    fi
    say "zerohead is not installed in $install_dir, so there is nothing to remove."
    return
  fi
  # This stops and removes the service and says where its data is.
  "$program" service uninstall </dev/null || fail "The service could not be removed (see above), so the program was kept."
  rm -f "$program"
  say "Removed $program."
}

# Downloads $1 to $2. From an https address, only over https, redirects included.
fetch() {
  case "$1" in
    https://*) secure=yes ;;
    *) secure=no ;;
  esac
  if command -v curl >/dev/null 2>&1; then
    if [ "$secure" = yes ]; then
      curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL -o "$2" "$1" </dev/null || fail "Could not download $1."
    else
      curl -fsSL -o "$2" "$1" </dev/null || fail "Could not download $1."
    fi
  elif wget --version 2>/dev/null | grep -q 'GNU Wget'; then
    if [ "$secure" = yes ]; then
      wget -q --tries=3 --https-only -O "$2" "$1" </dev/null || fail "Could not download $1."
    else
      wget -q --tries=3 -O "$2" "$1" </dev/null || fail "Could not download $1."
    fi
  else
    fail "Installing zerohead needs curl or GNU wget."
  fi
}

# The SHA-256 of $1, in lower-case hex.
sha256() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | cut -d' ' -f1
  else
    fail "Installing zerohead needs sha256sum or shasum, to check the download."
  fi
}

cleanup() {
  rm -rf "${tmp:-}"
  [ -z "${new:-}" ] || rm -f "$new"
}

say() {
  printf '%s\n' "$1"
}

fail() {
  say "$1" >&2
  exit 1
}

main "$@"
}
