#!/bin/sh
# Installs the webhooklocal CLI (webhooklocal, with the alias wl).
#
#   curl -fsSL https://webhooklocal.com/install.sh | sh
#
# Installs into ~/.local/bin, or $WL_INSTALL_DIR. Never uses sudo. The
# download is checked against checksums.txt from the same server.
set -eu

base="${WL_BASE_URL:-https://webhooklocal.com}"
dir="${WL_INSTALL_DIR:-$HOME/.local/bin}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch=$(uname -m)
case "$os" in
  darwin|linux) ;;
  *) echo "Unsupported operating system: $os. Download a binary from $base/docs#install instead." >&2; exit 1 ;;
esac
case "$arch" in
  x86_64|amd64) arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) echo "Unsupported CPU architecture: $arch." >&2; exit 1 ;;
esac
file="wl-$os-$arch"

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

echo "Downloading $base/dl/$file"
curl -fsSL "$base/dl/$file" -o "$tmp/$file"
curl -fsSL "$base/dl/checksums.txt" -o "$tmp/checksums.txt"

expected=$(grep " $file\$" "$tmp/checksums.txt" | cut -d' ' -f1)
if [ -z "$expected" ]; then
  echo "No checksum listed for $file." >&2
  exit 1
fi
if command -v sha256sum >/dev/null 2>&1; then
  actual=$(sha256sum "$tmp/$file" | cut -d' ' -f1)
else
  actual=$(shasum -a 256 "$tmp/$file" | cut -d' ' -f1)
fi
if [ "$actual" != "$expected" ]; then
  echo "Checksum mismatch for $file: expected $expected, got $actual. Nothing was installed." >&2
  exit 1
fi

mkdir -p "$dir"
install -m 755 "$tmp/$file" "$dir/webhooklocal"
ln -sf webhooklocal "$dir/wl"

echo "Installed $("$dir/wl" version) to $dir"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) echo "Add it to your PATH, for example in your shell profile:"; echo "  export PATH=\"$dir:\$PATH\"" ;;
esac
echo "Next: wl login"
