#!/bin/sh
# Jetsyn CLI installer.
#
#   curl -fsSL https://jetsyn.ai/install | sh
#
# Downloads the `jetsyn` CLI from the Jetsyn site, installs it to a directory
# on your PATH that you can write, and makes it executable. Idempotent: rerun
# any time to upgrade to the latest CLI. POSIX sh, no dependencies beyond a
# downloader (curl or wget).
#
# Overrides (optional):
#   JETSYN_BASE_URL   where to fetch from   (default: https://jetsyn.ai)
#   JETSYN_BIN_DIR    where to install to   (default: ~/.local/bin, then /usr/local/bin)

set -eu

BASE_URL="${JETSYN_BASE_URL:-https://jetsyn.ai}"
# strip any trailing slash so "$BASE_URL/jetsyn" is always well-formed
BASE_URL="${BASE_URL%/}"
SRC_URL="$BASE_URL/jetsyn"

# --- pretty output (degrade to plain on non-tty / NO_COLOR / dumb term) -------
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != "dumb" ]; then
  BOLD="$(printf '\033[1m')"; DIM="$(printf '\033[2m')"; RST="$(printf '\033[0m')"
  CYAN="$(printf '\033[36m')"; GREEN="$(printf '\033[32m')"; RED="$(printf '\033[31m')"; YELLOW="$(printf '\033[33m')"
else
  BOLD=""; DIM=""; RST=""; CYAN=""; GREEN=""; RED=""; YELLOW=""
fi
say()  { printf '%s\n' "$*"; }
info() { printf '%s==>%s %s\n' "$CYAN" "$RST" "$*"; }
ok()   { printf '%s✓%s %s\n'  "$GREEN" "$RST" "$*"; }
warn() { printf '%s!%s %s\n'  "$YELLOW" "$RST" "$*"; }
die()  { printf '%s✖%s %s\n'  "$RED" "$RST" "$*" 1>&2; exit 1; }

# --- pick a downloader --------------------------------------------------------
# fetch <url> <dest> — download url to a file, failing hard on HTTP errors.
if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -qO "$2" "$1"; }
else
  die "need curl or wget to download the Jetsyn CLI. Install one and rerun."
fi

# --- choose an install dir the user can write --------------------------------
# Honor JETSYN_BIN_DIR if set; otherwise prefer ~/.local/bin (no sudo), then
# fall back to /usr/local/bin (may need sudo, noted below).
SUDO=""
if [ -n "${JETSYN_BIN_DIR:-}" ]; then
  BIN_DIR="$JETSYN_BIN_DIR"
  mkdir -p "$BIN_DIR" 2>/dev/null || die "cannot create $BIN_DIR. Pick another JETSYN_BIN_DIR."
  [ -w "$BIN_DIR" ] || die "$BIN_DIR is not writable. Pick another JETSYN_BIN_DIR or fix permissions."
else
  BIN_DIR="$HOME/.local/bin"
  if mkdir -p "$BIN_DIR" 2>/dev/null && [ -w "$BIN_DIR" ]; then
    :
  elif [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
    BIN_DIR="/usr/local/bin"
  else
    # last resort: /usr/local/bin via sudo (if available)
    BIN_DIR="/usr/local/bin"
    if command -v sudo >/dev/null 2>&1; then
      SUDO="sudo"
      warn "installing to $BIN_DIR (needs sudo). You may be prompted for your password."
    else
      die "no writable install dir found. Set JETSYN_BIN_DIR=<dir on your PATH> and rerun."
    fi
  fi
fi

DEST="$BIN_DIR/jetsyn"

# --- download to a temp file, then move into place atomically ----------------
TMP="$(mktemp 2>/dev/null || printf '%s' "${TMPDIR:-/tmp}/jetsyn.$$")"
# best-effort cleanup of the temp file on any exit
trap 'rm -f "$TMP" 2>/dev/null || true' EXIT INT TERM

info "Downloading the Jetsyn CLI from $SRC_URL"
fetch "$SRC_URL" "$TMP" || die "download failed from $SRC_URL"
# sanity check: must be a non-empty shell script
[ -s "$TMP" ] || die "downloaded file is empty. Try again, or check $BASE_URL is reachable."
head -n 1 "$TMP" | grep -q '^#!' || die "downloaded file does not look like the jetsyn CLI. Aborting."

chmod +x "$TMP" 2>/dev/null || true
info "Installing to $DEST"
$SUDO mkdir -p "$BIN_DIR" 2>/dev/null || true
$SUDO mv "$TMP" "$DEST" || die "could not write $DEST"
$SUDO chmod +x "$DEST" || die "could not make $DEST executable"
trap - EXIT INT TERM

ok "Installed jetsyn to $DEST"

# --- PATH guidance ------------------------------------------------------------
on_path=0
case ":${PATH}:" in
  *":$BIN_DIR:"*) on_path=1 ;;
esac

say ""
ok "${BOLD}Jetsyn CLI is ready.${RST}"
say ""
if [ "$on_path" -eq 1 ]; then
  say "  Next, run:  ${BOLD}${GREEN}jetsyn${RST}"
else
  warn "$BIN_DIR is not on your PATH yet."
  say "  Add it (then open a new terminal):"
  say "    ${DIM}echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> ~/.profile${RST}"
  say ""
  say "  Or run it directly right now:"
  say "    ${BOLD}${GREEN}$DEST${RST}"
fi
say ""
say "  ${DIM}Then sign into Claude Code and go. \`jetsyn connect\` opens Claude Code${RST}"
say "  ${DIM}inside your secure cloud Jetsyn cell. \`jetsyn --help\` for everything.${RST}"
say ""
