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

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

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) arch="amd64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) echo "flit: unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
  linux|darwin) ;;
  *) echo "flit: 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 "Authenticate:  flit login   (opens ${FLIT_URL}/tokens)"
echo "Then:          flit                  # compose in \$EDITOR"
echo "         or:   flit 'a fleeting thought'"
