#!/bin/sh
# Foodoo CLI installer: curl -fsSL https://foodoo.fit/install.sh | sh
#
# Downloads the latest foodoo binary for this machine from api.foodoo.fit
# (foodoo-server src/routes/cli-releases.ts) and puts it in
# $FOODOO_INSTALL_DIR (default: ~/.local/bin). Set FOODOO_VERSION=0.1.0 for a
# given release.
set -eu

API="${FOODOO_API_URL:-https://api.foodoo.fit}/api/cli"
DIR="${FOODOO_INSTALL_DIR:-$HOME/.local/bin}"
VERSION="${FOODOO_VERSION:-latest}"

say() { printf '%s\n' "$*"; }
fail() { printf 'foodoo: %s\n' "$*" >&2; exit 1; }

case "$(uname -s)" in
    Darwin) os="darwin" ;;
    Linux) os="linux" ;;
    *) fail "unsupported system $(uname -s) — foodoo runs on macOS and Linux" ;;
esac
case "$(uname -m)" in
    arm64 | aarch64) arch="arm64" ;;
    x86_64 | amd64) arch="x64" ;;
    *) fail "unsupported processor $(uname -m) — foodoo runs on macOS and Linux" ;;
esac
# Rosetta: an Apple Silicon Mac running this shell as x86_64.
if [ "$os" = "darwin" ] && [ "$arch" = "x64" ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = "1" ]; then
    arch="arm64"
fi

asset="foodoo-$os-$arch"
url="$API/download/${VERSION#v}/$asset"

command -v curl >/dev/null 2>&1 || fail "curl is needed"
tmp="$(mktemp "${TMPDIR:-/tmp}/foodoo.XXXXXX")"
trap 'rm -f "$tmp" "$tmp.sha256"' EXIT INT TERM

say "Downloading ${asset}…"
curl -fSL --progress-bar "$url" -o "$tmp" || fail "download failed: $url"
if curl -fsSL "$url.sha256" -o "$tmp.sha256" 2>/dev/null; then
    expected="$(cut -d' ' -f1 < "$tmp.sha256")"
    if command -v shasum >/dev/null 2>&1; then
        actual="$(shasum -a 256 "$tmp" | cut -d' ' -f1)"
    else
        actual="$(sha256sum "$tmp" | cut -d' ' -f1)"
    fi
    [ "$expected" = "$actual" ] || fail "checksum mismatch — try again"
fi

mkdir -p "$DIR"
chmod +x "$tmp"
mv "$tmp" "$DIR/foodoo"
trap - EXIT INT TERM

say "Installed foodoo to $DIR/foodoo"
case ":$PATH:" in
    *":$DIR:"*) ;;
    *) say "Add it to your PATH:  export PATH=\"$DIR:\$PATH\"" ;;
esac
say "Next: foodoo login"
