#!/usr/bin/env sh
#
# Install the `tilizy` CLI. Served by the portal at https://app.tilizy.com/install —
# it is a downloader, not a secret, and it handles no API token.
#
#   curl -fsSL https://app.tilizy.com/install | sh                     # update / re-install
#   curl -fsSL https://app.tilizy.com/install | sh -s -- --token TOKEN # first install
#
# The token comes from either place, and both work the same way here:
#   · your onboarding link, if your account is being set up now
#   · Profile → Install the CLI, if you already have a portal account
#
# Once installed and logged in, nothing needs a token again: `tilizy
# self-update` authenticates with your saved portal session.
#
# Options:
#   --token <token>    install token, or your onboarding link/token
#   --invite <token>   the same thing under its older name
#   --version <v>      install a specific release (default: latest)
#   --bin <path>       install location (default: $HOME/.local/bin/tilizy)
#
# Re-running upgrades in place.

set -eu

PORTAL="https://app.tilizy.com"
BIN_PATH="${CLI_BIN_PATH:-$HOME/.local/bin/tilizy}"
INVITE="${TILIZY_INVITE:-}"
VERSION="${CLI_VERSION:-latest}"

# The invitation reaches people as a URL (…/portal/onboard/<token>), so
# accept either that or the bare token. Asking someone to copy one path
# segment out of a link they were sent is exactly the kind of step that
# turns a one-command install into a support conversation.
strip_invite() {
  case "$1" in
    *://*) printf '%s' "${1##*/}" ;;
    *) printf '%s' "$1" ;;
  esac
}

while [ $# -gt 0 ]; do
  case "$1" in
    --token|--invite) INVITE="$(strip_invite "${2:-}")"; shift 2 ;;
    --version) VERSION="${2:-latest}"; shift 2 ;;
    --bin) BIN_PATH="${2:-$BIN_PATH}"; shift 2 ;;
    -h|--help) sed -n '2,20p' "$0" 2>/dev/null || true; exit 0 ;;
    *) echo "unknown option: $1" >&2; exit 2 ;;
  esac
done

command -v curl >/dev/null 2>&1 || { echo "curl is required." >&2; exit 1; }

case "$(uname -s)" in
  Linux) OS=linux ;;
  Darwin) OS=darwin ;;
  *) echo "Unsupported OS: $(uname -s). Ask for a build, or build from source." >&2; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "Unsupported architecture: $(uname -m)." >&2; exit 1 ;;
esac

URL="$PORTAL/api/portal/cli/download?os=$OS&arch=$ARCH&version=$VERSION"

# An existing session is enough on a re-install; the invite covers the first
# one. Reading the saved token here (rather than asking for it) is what makes
# `curl … | sh` idempotent for someone already set up.
AUTH=""
if [ -n "$INVITE" ]; then
  AUTH="$INVITE"
elif [ -r "${XDG_CONFIG_HOME:-$HOME/.config}/tilizy/cli.json" ]; then
  AUTH="$(sed -n 's/.*"token"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
    "${XDG_CONFIG_HOME:-$HOME/.config}/tilizy/cli.json" | head -n1)"
fi
if [ -z "$AUTH" ]; then
  echo "No install token and no saved portal session." >&2
  echo "Get one from $PORTAL/portal/profile (Install the CLI), then:" >&2
  echo "  curl -fsSL $PORTAL/install | sh -s -- --token <token>" >&2
  exit 1
fi

TMP_BIN="$(mktemp)"
trap 'rm -f "$TMP_BIN"' EXIT INT TERM

# Brace any expansion touching a non-ASCII char: macOS /bin/sh is bash 3.2,
# which swallows the following UTF-8 bytes into the variable name.
echo "Downloading tilizy ($OS/$ARCH) from ${PORTAL}…"
HTTP_CODE="$(curl --fail-with-body --location --silent --show-error \
  --header "Authorization: Bearer $AUTH" \
  --write-out '%{http_code}' \
  "$URL" -o "$TMP_BIN" 2>/dev/null || true)"

if [ "$HTTP_CODE" != "200" ] || [ ! -s "$TMP_BIN" ]; then
  echo "Download failed (HTTP ${HTTP_CODE:-000})." >&2
  # The body carries the portal's own message on a 4xx — show it, it says
  # which of "expired invite" / "no such build" actually happened.
  if [ -s "$TMP_BIN" ]; then head -c 400 "$TMP_BIN" >&2; echo >&2; fi
  exit 1
fi

# Verify before installing. This is the FIRST install, on a machine with no
# prior trust in us — so it is the one that most needs an integrity check,
# and it was the one that had none while self-update verified every upgrade.
#
# A missing sidecar is an ops gap and only warns; a MISMATCH is refused. The
# asymmetry is deliberate: not publishing a checksum is our mistake, but a
# checksum that disagrees is the only signal we would ever get that the bytes
# are not ours.
sha_of() {
  if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | cut -d' ' -f1
  else printf ''
  fi
}

EXPECTED="$(curl --fail --location --silent \
  --header "Authorization: Bearer $AUTH" \
  "$URL&checksum=1" 2>/dev/null | tr -d '[:space:]' | cut -c1-64 || true)"
ACTUAL="$(sha_of "$TMP_BIN")"

if [ -z "$EXPECTED" ]; then
  echo "⚠  No published checksum for this build — installing unverified." >&2
elif [ -z "$ACTUAL" ]; then
  echo "⚠  No sha256 tool on this machine — installing unverified." >&2
elif [ "$EXPECTED" != "$ACTUAL" ]; then
  echo "✗ Checksum mismatch — NOT installing." >&2
  echo "  expected $EXPECTED" >&2
  echo "  got      $ACTUAL" >&2
  exit 1
else
  echo "✓ Checksum verified."
fi

mkdir -p "$(dirname "$BIN_PATH")"
# Install to a temp name in the destination dir, then rename: a running
# binary cannot be overwritten in place on every platform.
install -m 0755 "$TMP_BIN" "$BIN_PATH.new"
mv -f "$BIN_PATH.new" "$BIN_PATH"

echo
echo "Installed: $BIN_PATH"
"$BIN_PATH" --version 2>/dev/null || true

case ":$PATH:" in
  *:"$(dirname "$BIN_PATH")":*) ;;
  *)
    RC_FILE="$HOME/.bashrc"
    case "${SHELL:-}" in *zsh) RC_FILE="$HOME/.zshrc" ;; esac
    echo
    echo "⚠  $(dirname "$BIN_PATH") is not on PATH. Add it:"
    echo
    echo "   echo 'export PATH=\"$(dirname "$BIN_PATH"):\$PATH\"' >> $RC_FILE"
    ;;
esac

echo
echo "Next:  tilizy login        # browser handshake, no token to paste"
echo "       tilizy onboard      # your onboarding checklist, start to finish"
