#!/bin/sh
# Install the `hush` CLI.
#   curl -fsSL https://synk.sh/hush | sh
# Env:
#   SYNK_URL   where the binaries live (default https://synk.sh)
#   HUSH_URL   the Hush service, for the token hint (default https://app.synk.it/hush)
#   PREFIX     install dir (default /usr/local/bin, falls back to ~/.local/bin)
set -eu

SYNK_URL="${SYNK_URL:-https://synk.sh}"
HUSH_URL="${HUSH_URL:-https://app.synk.it/hush}"
BIN="hush"

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) arch="amd64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) echo "hush: unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
  linux|darwin) ;;
  *) echo "hush: unsupported OS: $os" >&2; exit 1 ;;
esac

prefix="${PREFIX:-/usr/local/bin}"
if [ ! -w "$prefix" ] 2>/dev/null; then
  if [ "$(id -u)" -eq 0 ]; then :; else
    prefix="$HOME/.local/bin"
    mkdir -p "$prefix"
  fi
fi

url="$SYNK_URL/dl/$BIN-$os-$arch"
tmp="$(mktemp)"
echo "Downloading $url"
curl -fsSL "$url" -o "$tmp"
chmod +x "$tmp"

dest="$prefix/$BIN"
if mv "$tmp" "$dest" 2>/dev/null; then :; else
  echo "Installing to $dest (needs sudo)"
  sudo mv "$tmp" "$dest"
fi

echo "Installed $dest"
case ":$PATH:" in
  *":$prefix:"*) ;;
  *) echo "Note: $prefix is not on your PATH." ;;
esac
echo
echo "Mint a token at ${HUSH_URL}/tokens (sign in first), then save it:"
echo "  mkdir -p ~/.config/hush && printf %s '<TOKEN>' > ~/.config/hush/token && chmod 600 ~/.config/hush/token"
echo "Then: echo -n 'my secret' | hush --expire 1h --burn"
