#!/bin/sh
# FuzzyShare CLI installer. Usage:  curl -fsSL https://fuzzyshare.com/install.sh | sh
#
# Downloads the fuzzy binary for this machine from https://fuzzyshare.com, checks its SHA-256 against
# https://fuzzyshare.com/dl/checksums.txt, and installs it. Settings (environment):
#   FUZZY_INSTALL_DIR   where to put the binary (default: /usr/local/bin if writable,
#                      else ~/.local/bin). This script never runs sudo.
# Everything is inside main, which runs on the last line: a download cut short never executes.
set -eu

BASE='https://fuzzyshare.com'

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

have() { command -v "$1" >/dev/null 2>&1; }

# fetch URL DEST: curl or wget, failing on HTTP errors.
fetch() {
  if have curl; then
    curl -fsSL --retry 2 -o "$2" "$1" || return 1
  elif have wget; then
    wget -q -O "$2" "$1" || return 1
  else
    die "needs curl or wget to download files"
  fi
}

sha256_of() {
  if have sha256sum; then
    sha256sum "$1" | awk '{print $1}'
  elif have shasum; then
    shasum -a 256 "$1" | awk '{print $1}'
  else
    die "needs sha256sum or shasum to verify the download; refusing to install unverified code"
  fi
}

detect_platform() {
  os=$(uname -s | tr '[:upper:]' '[:lower:]')
  case "$os" in
    linux | darwin) ;;
    *) die "unsupported system '$os'. On Windows use PowerShell: irm $BASE/install.ps1 | iex" ;;
  esac
  arch=$(uname -m)
  case "$arch" in
    x86_64 | amd64) arch=amd64 ;;
    aarch64 | arm64 | armv8*) arch=arm64 ;;
    *) die "unsupported CPU '$arch' (fuzzy is built for amd64 and arm64)" ;;
  esac
  # a shell running under Rosetta reports x86_64 on an Apple Silicon Mac: take the native build
  if [ "$os" = darwin ] && [ "$arch" = amd64 ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || true)" = 1 ]; then
    arch=arm64
  fi
  name="fuzzy-$os-$arch"
}

pick_dir() {
  # SISO_INSTALL_DIR is the name from before the rename and still works
  if [ -n "${FUZZY_INSTALL_DIR:-${SISO_INSTALL_DIR:-}}" ]; then
    dir=${FUZZY_INSTALL_DIR:-$SISO_INSTALL_DIR}
  elif [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
    dir=/usr/local/bin
  else
    [ -n "${HOME:-}" ] || die "HOME is not set; set FUZZY_INSTALL_DIR to a directory to install into"
    dir=$HOME/.local/bin
  fi
  mkdir -p "$dir" 2>/dev/null || true
  [ -d "$dir" ] && [ -w "$dir" ] || die "cannot write to $dir. Set FUZZY_INSTALL_DIR to a directory you own, e.g. FUZZY_INSTALL_DIR=\$HOME/bin"
}

main() {
  detect_platform
  pick_dir

  tmp=$(mktemp -d "${TMPDIR:-/tmp}/fuzzy-install.XXXXXX") || die "cannot create a temporary directory"
  trap 'rm -rf "$tmp"' EXIT INT TERM

  say "Downloading $name from $BASE"
  fetch "$BASE/dl/$name" "$tmp/$name" || die "download failed: $BASE/dl/$name (is this server publishing binaries for $os/$arch?)"
  fetch "$BASE/dl/checksums.txt" "$tmp/checksums.txt" || die "download failed: $BASE/dl/checksums.txt"

  want=$(awk -v f="$name" '$2 == f || $2 == "*" f { print $1; exit }' "$tmp/checksums.txt")
  [ -n "$want" ] || die "checksums.txt has no entry for $name"
  got=$(sha256_of "$tmp/$name")
  if [ "$want" != "$got" ]; then
    die "checksum mismatch for $name (expected $want, got $got); nothing was installed"
  fi
  say "Checksum verified (sha256 $got)"

  dest=$dir/fuzzy
  # write next to the target, then rename: the swap is atomic, so a running fuzzy is never half-replaced
  cp "$tmp/$name" "$dir/.fuzzy.new.$$" || die "cannot write to $dir"
  chmod 755 "$dir/.fuzzy.new.$$"
  mv -f "$dir/.fuzzy.new.$$" "$dest" || { rm -f "$dir/.fuzzy.new.$$"; die "cannot install to $dest"; }

  # An earlier install under the old name gets a link, so 'siso' keeps working.
  if [ -e "$dir/siso" ] || [ -L "$dir/siso" ]; then ln -sf fuzzy "$dir/siso" 2>/dev/null || true; fi

  say "Installed $dest"
  ver=$("$dest" version 2>&1) || die "the installed binary does not run on this machine: $ver"
  say "$(printf '%s\n' "$ver" | sed -n 1p)"

  cmd=fuzzy
  case ":${PATH:-}:" in
    *":$dir:"*) ;;
    *)
      cmd=$dest
      say ""
      say "$dir is not on your PATH. Add it, for example:"
      say "  export PATH=\"$dir:\$PATH\"     # put this line in ~/.profile, ~/.zshrc or ~/.bashrc"
      ;;
  esac
  # Remember this server so 'fuzzy login' only has to ask for the access key. An existing choice is
  # never overwritten, and a failure here never fails the install.
  "$dest" server --if-unset --no-check "$BASE" >/dev/null 2>&1 || true
  say ""
  say "Next step:"
  if [ "$("$dest" server 2>/dev/null || true)" = "$BASE" ]; then
    say "  $cmd login"
    say "No account yet? Create one (it prints your key once and saves it for you):"
    say "  $cmd register --name \"Your Name\" --email you@example.com"
  else
    say "  $cmd login --url $BASE"
    say "No account yet? Create one (it prints your key once and saves it for you):"
    say "  $cmd register --url $BASE --name \"Your Name\" --email you@example.com"
  fi
  say "Later, 'fuzzy update' brings the CLI up to date from this server."
}

main "$@"
