#!/bin/sh
# Download the signed Stageproof release and install it to ~/.local/bin.
set -eu
version=v0.9.0
case "$(uname -s)" in
  Linux) ;;
  *)
    echo "stageproof: this script is for Linux. On macOS: brew install stageproof/stageproof/stageproof" >&2
    exit 1
    ;;
esac
case "$(uname -m)" in
  x86_64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *)
    echo "stageproof: unsupported architecture $(uname -m)" >&2
    exit 1
    ;;
esac
plain=${version#v}
archive="stageproof_${plain}_linux_${arch}.tar.gz"
url="https://github.com/stageproof/stageproof/releases/download/${version}"
dest="${HOME}/.local/bin"
mkdir -p "${dest}"
work=$(mktemp -d)
trap 'rm -rf "${work}"' EXIT
curl -fsSL -o "${work}/checksums.txt" "${url}/checksums.txt"
curl -fsSL -o "${work}/${archive}" "${url}/${archive}"
(
  cd "${work}"
  awk -v name="${archive}" '$2 == name { print; found=1 } END { exit !found }' checksums.txt > check-one.txt
  sha256sum -c check-one.txt >/dev/null
)
tar -xzf "${work}/${archive}" -C "${work}" stageproof
install -m 755 "${work}/stageproof" "${dest}/stageproof"
case "${SHELL:-}" in
  */zsh) rc="${HOME}/.zshrc" ;;
  */bash) rc="${HOME}/.bashrc" ;;
  *) rc="${HOME}/.profile" ;;
esac
if ! grep -F '.local/bin' "${rc}" >/dev/null 2>&1; then
  printf '\nexport PATH="${HOME}/.local/bin:${PATH}"\n' >> "${rc}"
fi
"${dest}/stageproof" version
