#!/bin/sh
set -eu
umask 077
version='0.1.1'
receipt='https://interplane.io/drakestapleton/interplane-forge/releases/tag/bring-v0.1.1'
target="$(uname -s)-$(uname -m)"
case "$target" in
Linux-aarch64)
url='https://interplane.io/drakestapleton/interplane-forge/releases/download/bring-v0.1.1/interplane-linux-aarch64'
expected='2377c1c75445eca63eee612a7df01c1fc2f7c8f64d0814425c5cc294894da028'
;;
Linux-x86_64)
url='https://interplane.io/drakestapleton/interplane-forge/releases/download/bring-v0.1.1/interplane-linux-x86_64'
expected='831cc137d0c1e45b75b5d60e1cb18b9d364f332e84ae261860fe8cfb4e2c62b6'
;;
Darwin-arm64)
url='https://interplane.io/drakestapleton/interplane-forge/releases/download/bring-v0.1.1/interplane-macos-arm64'
expected='7d26a5a2961eb878cfa409bdf1056a7ec74c3b5e8b07dcefc4d01cb481f74273'
;;
*) echo 'This platform has no Interplane release yet.' >&2; exit 1;;
esac
d=$(mktemp -d)
trap 'rm -f "$d/interplane"; rmdir "$d"' EXIT
trap 'exit 1' HUP INT TERM
while :; do
  code=$(curl -q --proto '=https' --proto-redir '=https' -sSL -o "$d/interplane" -w '%{http_code}' "$url") || code=000
  case $code in
  200) break;;
  503|502|504|429) echo 'The download server is busy; trying again in 10 seconds.' >&2; sleep 10;;
  *) echo "The download failed with HTTP $code. Nothing was run." >&2; exit 1;;
  esac
done
if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$d/interplane")
else
  actual=$(shasum -a 256 "$d/interplane")
fi
actual=${actual%% *}
printf 'Interplane %s\nDownloaded SHA-256: %s\nExpected SHA-256:   %s\nCompare with: %s\n' "$version" "$actual" "$expected" "$receipt"
[ "$actual" = "$expected" ] || { echo 'Fingerprint mismatch. Nothing was run.' >&2; exit 1; }
chmod 700 "$d/interplane"
"$d/interplane" get "$@" < /dev/tty
