#!/usr/bin/env sh
# AMerc TinyBox consumer installer 0.5.295-ttyfix
set -eu
AMERC_BASE=${AMERC_BASE_URL:-https://amerc.ai}
if [ -z "${HOME:-}" ]; then
  HOME=$(getent passwd "$(id -u)" 2>/dev/null | cut -d: -f6)
  [ -n "$HOME" ] || { printf 'HOME is not set and could not be resolved.\n' >&2; exit 1; }
  export HOME
fi
INSTALL_ROOT=${AMERC_TINYBOX_HOME:-"$HOME/.local/share/amerc/tinybox"}
BIN_ROOT=${AMERC_USER_BIN:-"$HOME/.local/bin"}
# Piped through `curl | sh`, stdin holds THIS SCRIPT — a bare `read` would eat
# the next script line and exit at the first prompt. Read from the terminal;
# AMERC_USERNAME / AMERC_PASSWORD keep headless installs possible.
if [ -t 0 ]; then
  TTY_IN=''
elif ( : </dev/tty ) 2>/dev/null; then
  TTY_IN='/dev/tty'
else
  TTY_IN='none'
fi
read_tty() { # $1 = variable name
  if [ "$TTY_IN" = '/dev/tty' ]; then IFS= read -r "$1" </dev/tty; else IFS= read -r "$1"; fi
}
stty_tty() {
  if [ "$TTY_IN" = '/dev/tty' ]; then stty "$@" </dev/tty 2>/dev/null || true
  else stty "$@" 2>/dev/null || true; fi
}
amerc_user=${AMERC_USERNAME:-}
amerc_password=${AMERC_PASSWORD:-}
if [ -z "$amerc_user" ] || [ -z "$amerc_password" ]; then
  if [ "$TTY_IN" = 'none' ]; then
    printf 'No terminal is available for prompts. Set AMERC_USERNAME and AMERC_PASSWORD and rerun.\n' >&2
    exit 1
  fi
  if [ -z "$amerc_user" ]; then
    printf 'AMerc account username: ' >&2
    read_tty amerc_user
  fi
  if [ -z "$amerc_password" ]; then
    printf 'AMerc account password: ' >&2
    stty_tty -echo
    read_tty amerc_password
    stty_tty echo
    printf '\n' >&2
  fi
fi
cookie_file=$(mktemp "${TMPDIR:-/tmp}/amerc-tinybox-cookie.XXXXXX")
package_file=$(mktemp "${TMPDIR:-/tmp}/amerc-tinybox.XXXXXX.tar.gz")
cleanup() { rm -f "$cookie_file" "$package_file"; }
trap cleanup EXIT HUP INT TERM
curl -fsS -L -c "$cookie_file" -b "$cookie_file" -o /dev/null \
  --data-urlencode "username=$amerc_user" --data-urlencode "password=$amerc_password" "$AMERC_BASE/login"
curl -fsS -L -b "$cookie_file" -o "$package_file" "$AMERC_BASE/downloads/consumer.tar.gz"
mkdir -p "$INSTALL_ROOT" "$BIN_ROOT"
tar -xzf "$package_file" -C "$INSTALL_ROOT"
chmod 700 "$INSTALL_ROOT/tinybox-consumer" 2>/dev/null || true
wrapper="$BIN_ROOT/tinybox_consumer"
printf '%s\n' '#!/usr/bin/env sh' "exec \"$INSTALL_ROOT/tinybox-consumer\" --config \"$INSTALL_ROOT/consumer.json\" \"\$@\"" >"$wrapper"
chmod 700 "$wrapper"
ln -sf "$wrapper" "$BIN_ROOT/tinybox-consumer"
printf 'Installed. Start with: tinybox_consumer --pool claude\n'
printf 'If %s is not on PATH, add: export PATH="$HOME/.local/bin:$PATH"\n' "$BIN_ROOT"
printf 'Manual: %s/downloads/tinybox-manual.md\n' "$AMERC_BASE"
