#!/bin/sh
# Installs hardrev's command, hr, for this user (no root):
#
#   curl -fsSL https://hardrev.dev/install.sh | sh
#   curl -fsSL https://hardrev.dev/install.sh | sh -s -- --uninstall
#
# Run it again to update. It brings its own Node.js, so it needs none and ignores which one you use.
# Both downloads are checked against the SHA-256 sums below before anything is replaced.
#
#   HARDREV_HOME  where it goes            (default ~/.local/share/hardrev)
#   HARDREV_BIN   where the hr command goes (default ~/.local/bin)
#   HARDREV_NODE  a Node.js 22.15 or newer to use instead of downloading one
#   HARDREV_URL   where to download from    (default https://hardrev.dev)
#
# In the repository this is apps/cli/install/install.sh; scripts/bundle.mjs fills in the @NAME@ values.
# ASCII only: macOS's sh (bash 3.2) takes a non-ASCII character after $NAME as part of the name.
set -eu

VERSION='0.1.0'
BUNDLE='hardrev/hr-5f0350b78cf8.tar.gz'
BUNDLE_SHA256='5f0350b78cf87279f3a1a35f973abdfb98d8ae694f91d12a1604c70572f3c100'
NODE_VERSION='22.23.5'
MARK='# Made by hardrev install.sh'

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

fetch() { # url file
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --retry 2 -o "$2" "$1" || die "could not download $1"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$2" "$1" || die "could not download $1"
  else
    die "needs curl or wget"
  fi
}

check() { # file sha256
  if command -v sha256sum >/dev/null 2>&1; then
    sum=$(sha256sum <"$1")
  elif command -v shasum >/dev/null 2>&1; then
    sum=$(shasum -a 256 <"$1")
  else
    die "needs sha256sum or shasum to check the download"
  fi
  [ "${sum%% *}" = "$2" ] || die "the download is not what was expected (wrong checksum); nothing was changed. Try again."
}

node_platform() {
  case "$(uname -s)" in
    Linux) os=linux ;;
    Darwin) os=darwin ;;
    *) die "there is no hr for $(uname -s); on Windows use WSL" ;;
  esac
  case "$(uname -m)" in
    x86_64 | amd64) arch=x64 ;;
    aarch64 | arm64) arch=arm64 ;;
    *) die "no Node.js to download for $(uname -m); set HARDREV_NODE to one you have (22.15 or newer)" ;;
  esac
  if [ "$os" = linux ] && [ -n "$(find /lib -maxdepth 1 -name 'ld-musl-*' 2>/dev/null)" ]; then
    die "this system uses musl (Alpine?): install Node.js 22.15 or newer, then run this with HARDREV_NODE=\$(command -v node)"
  fi
  printf '%s-%s' "$os" "$arch"
}

# From https://nodejs.org/dist/v22.23.5/SHASUMS256.txt
node_sha256() {
  case "$1" in
    darwin-arm64) printf e7131995759b61a0170b646010d2ad35a5d37b4cb0d471f3e8317eac6f742f3d ;;
    darwin-x64) printf c53383238206b9ae4db23c5d8a63645e2e753bec8ab51a49cc81939aa64e9422 ;;
    linux-arm64) printf 8bd3dc69eee8f3f226315a80d7d1d4faccf217a4c8fae500168ac2e38f3bdba3 ;;
    linux-x64) printf c54118104acc524633b5abe106bbf44a53126ec8b4e5fa105cb92b5d7de8a1a1 ;;
  esac
}

node_ok() { "$1" -e 'const [a, b] = process.versions.node.split("."); process.exit(a > 22 || (a == 22 && b >= 15) ? 0 : 1)' >/dev/null 2>&1; }

# A path as one single-quoted shell word.
quote() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }

ours() { [ -f "$1" ] && grep -qF "$MARK" "$1"; }

# Removes the folders this script made in $home, except the two given. Nothing else in $home is touched.
clean() {
  for d in "$home"/release-* "$home"/node-v*; do
    [ -d "$d" ] || continue
    [ "$d" = "${1-}" ] || [ "$d" = "${2-}" ] || rm -rf -- "$d"
  done
}

uninstall() {
  if ours "$bin/hr"; then rm -f -- "$bin/hr"; fi
  clean
  rmdir -- "$home" 2>/dev/null || true
  say "hr is removed. Your repositories, settings and login were not touched."
}

main() {
  [ -n "${HOME-}" ] || die "HOME is not set"
  home=${HARDREV_HOME:-$HOME/.local/share/hardrev}
  bin=${HARDREV_BIN:-$HOME/.local/bin}
  url=${HARDREV_URL:-https://hardrev.dev}
  case "$home" in /*) ;; *) die "HARDREV_HOME must be an absolute path" ;; esac
  case "$bin" in /*) ;; *) die "HARDREV_BIN must be an absolute path" ;; esac
  case "$url" in
    https://* | http://localhost:* | http://127.0.0.1:*) ;;
    *) die "HARDREV_URL must start with https://" ;;
  esac
  case "${1-}" in
    '') ;;
    --uninstall)
      uninstall
      return
      ;;
    *) die "unknown option $1 (the only one is --uninstall)" ;;
  esac

  # Before downloading anything: an hr that is not ours stays.
  if { [ -e "$bin/hr" ] || [ -L "$bin/hr" ]; } && ! ours "$bin/hr"; then
    die "$bin/hr already exists and was not made by this installer. Remove it, or set HARDREV_BIN to another folder."
  fi
  command -v tar >/dev/null 2>&1 || die "needs tar"

  mkdir -p -- "$home" "$bin"
  tmp=$(mktemp -d "$home/tmp.XXXXXX")
  trap 'rm -rf -- "$tmp"' EXIT
  trap 'exit 1' HUP INT TERM

  if [ -n "${HARDREV_NODE-}" ]; then
    case "$HARDREV_NODE" in /*) ;; *) die "HARDREV_NODE must be an absolute path" ;; esac
    node_ok "$HARDREV_NODE" || die "$HARDREV_NODE is not Node.js 22.15 or newer"
    node=$HARDREV_NODE
    node_dir=
  else
    platform=$(node_platform)
    node_dir=$home/node-v$NODE_VERSION
    node=$node_dir/bin/node
    if ! node_ok "$node"; then
      say "Downloading Node.js $NODE_VERSION..."
      fetch "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-$platform.tar.gz" "$tmp/node.tgz"
      check "$tmp/node.tgz" "$(node_sha256 "$platform")"
      mkdir "$tmp/node"
      tar -xzf "$tmp/node.tgz" -C "$tmp/node" --strip-components 1 "node-v$NODE_VERSION-$platform/bin/node" "node-v$NODE_VERSION-$platform/LICENSE"
      node_ok "$tmp/node/bin/node" || die "the downloaded Node.js does not run here; set HARDREV_NODE to one you have (22.15 or newer)"
      rm -rf -- "$node_dir"
      mv -- "$tmp/node" "$node_dir"
    fi
  fi

  release=$home/release-$VERSION-$(printf '%.12s' "$BUNDLE_SHA256")
  if [ ! -d "$release" ]; then
    say "Downloading hr $VERSION..."
    fetch "$url/$BUNDLE" "$tmp/hr.tgz"
    check "$tmp/hr.tgz" "$BUNDLE_SHA256"
    mkdir "$tmp/release"
    tar -xzf "$tmp/hr.tgz" -C "$tmp/release"
    "$node" "$tmp/release/dist/hr.js" --version >/dev/null || die "the downloaded hr does not run here"
    mv -- "$tmp/release" "$release"
  fi

  {
    printf '#!/bin/sh\n%s; running it again updates hr.\n' "$MARK"
    printf 'exec %s %s "$@"\n' "$(quote "$node")" "$(quote "$release/dist/hr.js")"
  } >"$tmp/hr"
  chmod 755 "$tmp/hr"
  # Moved within $bin, so the command is replaced in one step even when $home is on another disk.
  cp -- "$tmp/hr" "$bin/.hr.$$"
  mv -f -- "$bin/.hr.$$" "$bin/hr"
  clean "$release" "$node_dir"

  say "Installed hr $VERSION in $bin."
  found=$(command -v hr 2>/dev/null || true)
  case ":${PATH-}:" in
    *":$bin:"*)
      if [ -n "$found" ] && ! [ "$found" -ef "$bin/hr" ]; then
        say "Another hr comes first on your PATH: $found. Remove it, or move $bin to the front of your PATH."
      fi
      ;;
    *) say "Add it to your PATH: put this in your shell's startup file (such as ~/.profile or ~/.zshrc):
  export PATH=$(quote "$bin"):\"\$PATH\"" ;;
  esac
  say "Next: hr login"
}

main "$@"
