#!/bin/sh
# Install the nulltransfer CLI on Linux or macOS: download the executable for this machine, check its
# SHA-256 against the release's SHA256SUMS, and put it in ~/.local/bin (or $NULLTRANSFER_INSTALL_DIR).
# Read it first if you like: https://nulltransfer.com/cli/install.sh
#
#   curl -fsSL https://nulltransfer.com/cli/install.sh | sh
set -eu

BASE="${NULLTRANSFER_CLI_BASE:-https://nulltransfer.com/cli}"
DIR="${NULLTRANSFER_INSTALL_DIR:-$HOME/.local/bin}"

say() { printf 'nulltransfer: %s\n' "$*" >&2; }

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *) say "no build for $(uname -s). On Windows run install.ps1 in PowerShell."; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=x64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) say "no build for $(uname -m)."; exit 1 ;;
esac
file="nulltransfer-$os-$arch"

# One version for both downloads, so a release landing in between cannot mix them up.
version=$(curl -fsSL "$BASE/latest.json" | sed -n 's/.*"version": *"\([0-9.]*\)".*/\1/p' | head -n 1)
[ -n "$version" ] || { say "could not read the latest version from $BASE/latest.json"; exit 1; }

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT INT TERM
say "downloading $file $version"
curl -fsSL "$BASE/v$version/$os-$arch" -o "$tmp/$file"
curl -fsSL "$BASE/v$version/SHA256SUMS" -o "$tmp/SHA256SUMS"

want=$(awk -v f="$file" '$2 == f { print $1 }' "$tmp/SHA256SUMS")
if command -v sha256sum >/dev/null 2>&1; then
  got=$(sha256sum "$tmp/$file" | awk '{ print $1 }')
else
  got=$(shasum -a 256 "$tmp/$file" | awk '{ print $1 }')
fi
if [ -z "$want" ] || [ "$want" != "$got" ]; then
  say "checksum mismatch for $file: expected ${want:-nothing}, got $got. Nothing was installed."
  exit 1
fi
say "checksum ok: $got"

mkdir -p "$DIR"
chmod 755 "$tmp/$file"
mv "$tmp/$file" "$DIR/nulltransfer"
say "installed $DIR/nulltransfer"
case ":$PATH:" in
  *":$DIR:"*) ;;
  *) say "add it to your PATH: echo 'export PATH=\"$DIR:\$PATH\"' >> ~/.profile (then open a new terminal)" ;;
esac
"$DIR/nulltransfer" version
