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

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

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$arch" in
  x86_64|amd64) arch="amd64" ;;
  arm64|aarch64) arch="arm64" ;;
  *) echo "farmfresh: unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
  linux|darwin) ;;
  *) echo "farmfresh: 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 "Bind a repo at ${FARMFRESH_URL}?tab=settings, then:"
echo "  farmfresh login          # paste a token from ${FARMFRESH_URL}/tokens"
echo "  farmfresh apply          # set this machine up"
echo "  farmfresh capture --merge  # snapshot its packages + changed dotfiles back"
