#!/bin/sh
# Installs tuckcap and its client tools, the newest release for this machine, checked against the release's
# SHA256SUMS, into $TUCKCAP_BIN, or ~/.local/bin:
#
#   curl -fsSL https://tuckcap.com/install.sh | sh
set -eu

base=${TUCKCAP_BASE:-https://tuckcap.com}
dir=${TUCKCAP_BIN:-$HOME/.local/bin}
fail() {
	echo "install.sh: $*" >&2
	exit 1
}

case $(uname -s) in
Darwin) os=darwin ;;
Linux) os=linux ;;
*) fail "no tuckcap for $(uname -s)" ;;
esac
case $(uname -m) in
x86_64 | amd64) arch=amd64 ;;
arm64 | aarch64) arch=arm64 ;;
*) fail "no tuckcap for $(uname -m)" ;;
esac
if command -v sha256sum >/dev/null; then
	sum() { sha256sum "$1" | cut -d' ' -f1; }
else
	sum() { shasum -a 256 "$1" | cut -d' ' -f1; }
fi

version=$(curl -fsSL "$base/latest")
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
curl -fsSL -o "$tmp/SHA256SUMS" "$base/$version/SHA256SUMS"
# Check all downloads before replacing any installed executable.
for bin in tuckcap tuckcap-tool-ssh-agent tuckcap-tool-git; do
	name=$bin-$os-$arch
	curl -fsSL -o "$tmp/$bin" "$base/$version/$name"
	want=$(awk -v f="$name" '$2 == f { print $1 }' "$tmp/SHA256SUMS")
	[ -n "$want" ] && [ "$(sum "$tmp/$bin")" = "$want" ] || fail "$name does not match the release's SHA256SUMS"
	chmod 755 "$tmp/$bin"
done

mkdir -p "$dir"
for bin in tuckcap-tool-ssh-agent tuckcap-tool-git tuckcap; do
	mv "$tmp/$bin" "$dir/$bin"
	echo "installed $bin $version at $dir/$bin"
done
case :$PATH: in
*:"$dir":*) ;;
*) echo "$dir is not on your PATH: add it, as with export PATH=\"$dir:\$PATH\"" ;;
esac
