#!/bin/sh
#
# Install uniji and uniji-service from the tap's GitHub releases, without Homebrew:
#
#   curl -fsSL https://uniji.sh | sh
#
#   UNIJI_VERSION=<0.x.y>    # default: the latest release
#   UNIJI_BIN_DIR=<dir>      # default: ~/.local/bin
#   UNIJI_RELEASES=<url>     # default: the tap's releases page
#
# docs/runbooks/release.md

set -eu

releases="${UNIJI_RELEASES:-https://github.com/non-identifie/homebrew-tap/releases}"
bin_dir="${UNIJI_BIN_DIR:-$HOME/.local/bin}"

fail() {
  echo "uniji install: $*" >&2
  exit 1
}

need() {
  command -v "$1" >/dev/null 2>&1 || fail "needs $1"
}

target() {
  os="$(uname -s)"
  arch="$(uname -m)"
  case "$os/$arch" in
    Linux/x86_64 | Linux/amd64) echo x86_64-unknown-linux-gnu ;;
    Linux/aarch64 | Linux/arm64) echo aarch64-unknown-linux-gnu ;;
    Darwin/arm64) echo aarch64-apple-darwin ;;
    *) fail "no release for $os $arch" ;;
  esac
}

latest_version() {
  url="$(curl -fsSLI -o /dev/null -w '%{url_effective}' "$releases/latest")" ||
    fail "could not reach $releases/latest"
  tag="${url##*/}"
  case "$tag" in
    v0.*) echo "${tag#v}" ;;
    *) fail "the latest release, '$tag', is not a uniji 0.x tag" ;;
  esac
}

sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | cut -d' ' -f1
  else
    shasum -a 256 "$1" | cut -d' ' -f1
  fi
}

on_path() {
  case ":$PATH:" in
    *":$1:"*) return 0 ;;
    *) return 1 ;;
  esac
}

main() {
  need curl
  need tar
  command -v sha256sum >/dev/null 2>&1 || need shasum

  triple="$(target)"
  version="${UNIJI_VERSION:-$(latest_version)}"
  tarball="uniji-$version-$triple.tar.gz"
  base="$releases/download/v$version"

  work="$(mktemp -d)"
  trap 'rm -rf "$work"' EXIT

  echo "Downloading uniji $version for $triple"
  curl -fsSL -o "$work/$tarball" "$base/$tarball" || fail "could not download $base/$tarball"
  curl -fsSL -o "$work/SHA256SUMS" "$base/SHA256SUMS" || fail "could not download $base/SHA256SUMS"

  expected="$(awk -v f="$tarball" '$2 == f { print $1 }' "$work/SHA256SUMS")"
  [ -n "$expected" ] || fail "SHA256SUMS has no line for $tarball"
  actual="$(sha256_of "$work/$tarball")"
  [ "$actual" = "$expected" ] || fail "$tarball checksum is $actual, SHA256SUMS says $expected"

  tar -xzf "$work/$tarball" -C "$work"
  mkdir -p "$bin_dir"
  cp "$work/uniji" "$bin_dir/uniji"
  cp "$work/lifecycle/uniji-service" "$bin_dir/uniji-service"
  chmod 755 "$bin_dir/uniji" "$bin_dir/uniji-service"

  echo "Installed $("$bin_dir/uniji" --version) to $bin_dir"
  on_path "$bin_dir" || echo "Add $bin_dir to PATH to run uniji by name."
  echo "Run 'uniji-service install' to keep the daemon running."
}

# The last line runs everything, so a download cut short by the pipe executes nothing.
main "$@"
