#!/bin/sh
# Tazmu server installer for macOS and Linux.
#
# Read it before you run it:
#   curl -fsSLO https://tazmu.xyz/install.sh && less install.sh && sh install.sh
#
# What it does:
#   1. Checks that Docker and Docker Compose v2 work for this user, asks how
#      you will reach the server, and picks a free port.
#   2. Logs Docker in to registry.tazmu.xyz with your server credential.
#   3. Writes compose.yaml, Caddyfile, .env, .env.secrets and update.sh into
#      ~/tazmu (or $TAZMU_DIR).
#   4. Creates the data volume, starts the server and waits until it is healthy.
#   5. Signs the server in with the same credential, so one installation
#      pulls images and checks the license, and installs the Codex and
#      Claude Code CLIs into the data volume.
#   6. Prints a one-time link that creates your account in the browser, then
#      walks you through your Tazmu subscription and AI sign-ins.
# It does not use sudo and changes nothing outside that folder and Docker.
#
# Without TAZMU_DOMAIN or TAZMU_PUBLIC_HOST, it asks whether the included Caddy
# should serve HTTPS for a domain, or your own proxy will, or neither.
#
# Settings, all optional:
#   TAZMU_DIR         install folder (default ~/tazmu)
#   TAZMU_NAME        Compose project and volume prefix (default tazmu)
#   TAZMU_PORT        port on 127.0.0.1 (default: the first free one of
#                     8080, 8090, 8180, 8280 and 18080)
#   TAZMU_DOMAIN      a DNS name pointing at this machine: serve HTTPS on
#                     ports 80 and 443 with a Let's Encrypt certificate
#   TAZMU_PUBLIC_HOST without TAZMU_DOMAIN: the host name your own HTTPS proxy
#                     serves, such as tazmu.example.com. The proxy forwards to
#                     127.0.0.1:$TAZMU_PORT and keeps the Host header.
#   TAZMU_VERSION     server version, 0.1.106 or later (default: the latest)
#   TAZMU_CREDENTIAL  server credential, instead of being asked for it
#   TAZMU_ENGINES     npm packages to install, "" for none
set -eu

REGISTRY=registry.tazmu.xyz
IMAGE=$REGISTRY/tazmu/server
RELEASES=https://accounts.tazmu.xyz/v1/releases/server
SITE=${TAZMU_SITE:-https://tazmu.xyz}
DIR=${TAZMU_DIR:-$HOME/tazmu}
NAME=${TAZMU_NAME:-tazmu}
PORT=${TAZMU_PORT:-}
# Tried in order when TAZMU_PORT is not set.
PORT_CHOICES="8080 8090 8180 8280 18080"
DOMAIN=${TAZMU_DOMAIN:-}
PUBLIC_HOST=$(printf '%s' "${TAZMU_PUBLIC_HOST:-}" | tr '[:upper:]' '[:lower:]')
# Older images do not put the engine CLIs in /data/.npm-global/bin on PATH.
MIN_VERSION=0.1.106
ENGINES=${TAZMU_ENGINES-@openai/codex @anthropic-ai/claude-code}

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

# True when there is a terminal to ask questions on.
can_ask() { (exec </dev/tty) 2>/dev/null; }

# Prints $1 on the terminal and reads an answer into REPLY; $2 is the default.
ask() {
  printf '%s' "$1" >/dev/tty
  read -r REPLY </dev/tty || REPLY=
  [ -n "$REPLY" ] || REPLY=${2:-}
}

# True when something already listens on TCP port $1.
port_busy() {
  if command -v ss >/dev/null 2>&1; then
    ss -ltn 2>/dev/null | awk -v p=":$1\$" '$4 ~ p { found = 1 } END { exit !found }' && return 0
  elif command -v lsof >/dev/null 2>&1; then
    lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1 && return 0
  fi
  # Also catches listeners those tools cannot see, such as another user's on
  # macOS. curl exits 7 only when nothing accepted the connection.
  if curl -s -o /dev/null --max-time 2 "http://127.0.0.1:$1/" 2>/dev/null; then return 0; else rc=$?; fi
  [ "$rc" -ne 7 ]
}

valid_port() {
  case $1 in
    "" | *[!0-9]*) return 1 ;;
  esac
  [ "$1" -ge 1 ] && [ "$1" -le 65535 ]
}

valid_host() {
  case $1 in
    *[!a-z0-9.-]* | "" | .* | *. | *..*) return 1 ;;
  esac
}

# Sets DOMAIN or PUBLIC_HOST from the answer to "how will you reach it?".
choose_access() {
  [ -z "$DOMAIN" ] && [ -z "$PUBLIC_HOST" ] && can_ask || return 0
  if port_busy 80 || port_busy 443; then default=2; else default=1; fi
  say ""
  say "How will you reach this server?"
  say "  1) The included Caddy serves HTTPS for a domain that points at this machine."
  say "     It needs ports 80 and 443 free."
  say "  2) Your own reverse proxy (nginx, Traefik, Caddy, Cloudflare Tunnel, Pangolin...)"
  say "     forwards a domain to a port on 127.0.0.1."
  say "  3) Only from this machine, at http://localhost."
  while :; do
    ask "Choose 1, 2 or 3 [$default]: " "$default"
    case $REPLY in
      1)
        if port_busy 80 || port_busy 443; then
          say "Ports 80 and 443 must be free for Caddy, and something already uses one of them."
          say "If a proxy runs here already, choose 2 and point it at Tazmu."
          continue
        fi
        while :; do
          ask "Domain that points at this machine, such as tazmu.example.com: "
          DOMAIN=$(printf '%s' "$REPLY" | tr '[:upper:]' '[:lower:]')
          valid_host "$DOMAIN" && break
          say "Enter a bare host name, without https:// or a path."
        done
        ;;
      2)
        while :; do
          ask "Host name your proxy serves, such as tazmu.example.com: "
          PUBLIC_HOST=$(printf '%s' "$REPLY" | tr '[:upper:]' '[:lower:]')
          valid_host "$PUBLIC_HOST" && break
          say "Enter a bare host name, without https:// or a path."
        done
        ;;
      3) ;;
      *) say "Type 1, 2 or 3."; continue ;;
    esac
    return 0
  done
}

# Sets PORT: TAZMU_PORT if it is free, or a free port from PORT_CHOICES.
choose_port() {
  if [ -n "$PORT" ]; then
    valid_port "$PORT" || die "TAZMU_PORT must be a port number from 1 to 65535."
    port_busy "$PORT" && die "port $PORT is already in use on this machine. Set TAZMU_PORT to a free port."
    return 0
  fi
  default=
  for candidate in $PORT_CHOICES; do
    if ! port_busy "$candidate"; then default=$candidate; break; fi
  done
  [ -n "$default" ] || die "ports $PORT_CHOICES are all in use. Set TAZMU_PORT to a free port."
  if ! can_ask; then
    PORT=$default
    [ "$PORT" = 8080 ] || say "Port 8080 is in use, so the server uses port $PORT."
    return 0
  fi
  while :; do
    ask "Port on 127.0.0.1 for the server [$default]: " "$default"
    if ! valid_port "$REPLY"; then say "Enter a port number from 1 to 65535."; continue; fi
    if port_busy "$REPLY"; then say "Port $REPLY is already in use. Pick another."; continue; fi
    PORT=$REPLY
    return 0
  done
}

# True when version $1 sorts before version $2 (numeric, dot by dot).
version_lt() {
  awk -v a="$1" -v b="$2" 'BEGIN {
    n = split(a, x, "."); m = split(b, y, "."); if (m > n) n = m
    for (i = 1; i <= n; i++) { if (x[i] + 0 < y[i] + 0) exit 0; if (x[i] + 0 > y[i] + 0) exit 1 }
    exit 1
  }'
}

check_version() {
  case $1 in
    [0-9]*.[0-9]*.[0-9]*) ;;
    *) die "'$1' is not a Tazmu version such as $MIN_VERSION." ;;
  esac
  case $1 in
    *[!0-9A-Za-z.+-]*) die "'$1' is not a Tazmu version such as $MIN_VERSION." ;;
  esac
  if version_lt "$1" "$MIN_VERSION"; then
    die "Tazmu $1 is too old for this installer: its engines are not on PATH, so no bot can run. Use $MIN_VERSION or later."
  fi
}

ask_credential() {
  if [ -n "${TAZMU_CREDENTIAL:-}" ]; then
    CREDENTIAL=$TAZMU_CREDENTIAL
    return
  fi
  [ -r /dev/tty ] || die "set TAZMU_CREDENTIAL; there is no terminal to ask on."
  say "Paste a server credential. Create one at https://accounts.tazmu.xyz/billing under Servers."
  printf 'Credential (hidden): ' >/dev/tty
  stty -echo </dev/tty
  trap 'stty echo </dev/tty' EXIT
  read -r CREDENTIAL </dev/tty
  stty echo </dev/tty
  trap - EXIT
  printf '\n' >/dev/tty
  [ -n "$CREDENTIAL" ] || die "no credential given."
}

# 1. Docker
command -v docker >/dev/null 2>&1 || die "Docker is not installed. Get it at https://docs.docker.com/get-docker/ and run this again."
docker info >/dev/null 2>&1 || die "Docker is not running, or this user may not use it."
docker compose version >/dev/null 2>&1 || die "Docker Compose v2 is missing ('docker compose version' failed)."
command -v curl >/dev/null 2>&1 || die "curl is missing."
[ ! -e "$DIR/compose.yaml" ] || die "$DIR already has an install. Run 'sh update.sh' there to update it."
DOMAIN=$(printf '%s' "$DOMAIN" | tr '[:upper:]' '[:lower:]')
[ -z "$DOMAIN" ] || [ -z "$PUBLIC_HOST" ] || die "set TAZMU_DOMAIN or TAZMU_PUBLIC_HOST, not both. With TAZMU_DOMAIN the installer's Caddy serves HTTPS itself."
[ -z "$DOMAIN" ] || valid_host "$DOMAIN" || die "TAZMU_DOMAIN must be a bare host name such as tazmu.example.com, without https:// or a path."
[ -z "$PUBLIC_HOST" ] || valid_host "$PUBLIC_HOST" || die "TAZMU_PUBLIC_HOST must be a bare host name such as tazmu.example.com, without https:// or a path."
choose_access
if [ -n "$DOMAIN" ]; then
  if port_busy 80 || port_busy 443; then
    die "Caddy needs ports 80 and 443 for $DOMAIN, and one is already in use. If a proxy runs here, set TAZMU_PUBLIC_HOST=$DOMAIN instead of TAZMU_DOMAIN and point the proxy at Tazmu."
  fi
else
  choose_port
fi

# 2. Version and registry login
VERSION=${TAZMU_VERSION:-$(curl -fsS "$RELEASES" | sed -n 's/.*"latest":"\([0-9][0-9.]*\)".*/\1/p')}
[ -n "$VERSION" ] || die "could not read the latest version from $RELEASES."
check_version "$VERSION"
say "Installing Tazmu server $VERSION into $DIR"
ask_credential
printf '%s' "$CREDENTIAL" | docker login "$REGISTRY" -u tazmu --password-stdin >/dev/null \
  || die "registry.tazmu.xyz refused the credential. Check it, or create a new one."
docker pull -q "$IMAGE:$VERSION" >/dev/null || die "could not pull $IMAGE:$VERSION."

# 3. Files
mkdir -p "$DIR"
cd "$DIR"
if [ -n "$DOMAIN" ]; then
  # Public HTTPS: Caddy answers on every interface and gets a certificate.
  HTTP=80 HTTPS=443 ADDRESS=$DOMAIN URL=https://$DOMAIN
else
  # Local only: plain HTTP on 127.0.0.1. Put your own HTTPS proxy in front.
  # HTTPS "127.0.0.1:" maps 443 to a random loopback port that nothing uses.
  HTTP=127.0.0.1:$PORT HTTPS=127.0.0.1: ADDRESS=:80 URL=http://localhost:$PORT
  # Behind your own HTTPS proxy, tell the app that requests for its host name
  # arrived over HTTPS, so browsers on that address pass the origin check.
  [ -z "$PUBLIC_HOST" ] || URL=https://$PUBLIC_HOST
fi
cat >.env <<EOF
COMPOSE_PROJECT_NAME=$NAME
TAZMU_VERSION=$VERSION
TAZMU_HTTP=$HTTP
TAZMU_HTTPS=$HTTPS
TAZMU_SITE_ADDRESS=$ADDRESS
TAZMU_PUBLIC_URL=$URL
TAZMU_PUBLIC_HOST=$PUBLIC_HOST
EOF
# Provider keys and other secrets for the server go here, readable only by you.
(umask 077 && : >>.env.secrets)

cat >Caddyfile <<'EOF'
{
	# The server's bots share this network namespace: keep the admin API
	# (localhost:2019) closed so they cannot rewrite the proxy.
	admin off
}

{$TAZMU_SITE_ADDRESS} {
	# Requests for TAZMU_PUBLIC_HOST came through your own HTTPS proxy on this
	# machine. Every other request keeps the scheme Caddy received it on.
	map {host} {tazmu_proto} {
		{$TAZMU_PUBLIC_HOST:https-disabled.invalid} https
		default {scheme}
	}
	encode zstd gzip
	handle /hooks/* {
		reverse_proxy 127.0.0.1:8800 {
			header_up X-Forwarded-Proto {tazmu_proto}
		}
	}
	handle {
		reverse_proxy 127.0.0.1:8799 {
			header_up X-Forwarded-Proto {tazmu_proto}
			flush_interval -1
		}
	}
}
EOF

cat >compose.yaml <<'EOF'
# Written by https://tazmu.xyz/install.sh. update.sh changes TAZMU_VERSION in .env.
name: ${COMPOSE_PROJECT_NAME}
services:
  # Owns the network namespace and the published port, so the server and
  # Caddy keep talking to each other when the server restarts.
  net:
    image: caddy:2
    command: ["sleep", "infinity"]
    init: true
    restart: unless-stopped
    read_only: true
    security_opt: ["no-new-privileges:true"]
    cap_drop: [ALL]
    ports: ["${TAZMU_HTTP}:80", "${TAZMU_HTTPS}:443"]
  omb:
    image: registry.tazmu.xyz/tazmu/server:${TAZMU_VERSION}
    init: true
    restart: unless-stopped
    read_only: true
    tmpfs: ["/tmp:mode=1777,size=1g"]
    security_opt: ["no-new-privileges:true"]
    cap_drop: [ALL]
    mem_limit: 4g
    pids_limit: 2048
    env_file: [{ path: .env.secrets, required: false }]
    volumes: ["data:/data"]
    network_mode: service:net
    environment:
      OMB_RESTART_ON_EXIT: "1"
      OMB_PUBLIC_URL: ${TAZMU_PUBLIC_URL}
      OMB_WEBHOOK_PUBLIC_URL: ${TAZMU_PUBLIC_URL}
      # Engine CLIs install into the data volume and survive updates.
      NPM_CONFIG_PREFIX: /data/.npm-global
  caddy:
    image: caddy:2
    restart: unless-stopped
    network_mode: service:net
    read_only: true
    tmpfs: ["/tmp:size=16m"]
    security_opt: ["no-new-privileges:true"]
    cap_drop: [ALL]
    cap_add: [NET_BIND_SERVICE]
    environment:
      TAZMU_SITE_ADDRESS: ${TAZMU_SITE_ADDRESS}
      TAZMU_PUBLIC_HOST: ${TAZMU_PUBLIC_HOST:-}
    depends_on: { omb: { condition: service_healthy } }
    volumes: ["./Caddyfile:/etc/caddy/Caddyfile:ro", "caddy_data:/data", "caddy_config:/config"]
volumes:
  # Created by install.sh and marked external, so `docker compose down -v`
  # cannot delete your data.
  data:
    external: true
    name: ${COMPOSE_PROJECT_NAME}_data
  caddy_data:
  caddy_config:
EOF

curl -fsSL "$SITE/update.sh" -o update.sh || die "could not download $SITE/update.sh."

# Caddy runs as root with every capability dropped, so it can only read the
# Caddyfile if everyone may. Set the modes here so a strict umask (077) does
# not leave Caddy restarting in a loop.
chmod 644 compose.yaml Caddyfile update.sh
chmod 600 .env .env.secrets

# 4. Data volume and start
# Compose prefers variables from the environment over .env. Unset the ones
# .env sets, so the file is the only source.
unset COMPOSE_PROJECT_NAME TAZMU_VERSION TAZMU_HTTP TAZMU_HTTPS TAZMU_SITE_ADDRESS TAZMU_PUBLIC_URL TAZMU_PUBLIC_HOST
docker volume create "${NAME}_data" >/dev/null
docker compose up -d --quiet-pull
say "Waiting for the server to report healthy..."
tries=0
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q omb)")" = healthy ]; do
  tries=$((tries + 1))
  [ "$tries" -le 60 ] || die "the server did not become healthy. See 'docker compose logs omb' in $DIR."
  sleep 3
done

# 5. The server checks its license with the credential Docker pulled with:
# one installation, one seat. Servers before 0.1.110 sign in from the
# browser instead.
printf '%s\n' "$CREDENTIAL" | docker compose exec -T omb node dist-server/tazmu.js license adopt >/dev/null 2>&1 || true

# Engine CLIs
if [ -n "$ENGINES" ]; then
  say "Installing $ENGINES..."
  # shellcheck disable=SC2086 # one word per package
  docker compose exec -T omb npm install -g --no-fund --no-audit --no-update-notifier --loglevel=error $ENGINES >/dev/null \
    || say "Engine install failed. Retry later: docker compose exec omb npm install -g $ENGINES"
fi

# 6. Setup link. Servers before 0.1.108 have no setup link; the server says so
# when someone already owns this data volume.
SETUP_LINK_COMMAND="docker compose exec omb node dist-server/tazmu.js account setup-link"
SETUP=$(docker compose exec -T omb node dist-server/tazmu.js account setup-link 2>/dev/null) || SETUP=

say ""
say "Tazmu $VERSION is running at $URL"
[ -z "$PUBLIC_HOST" ] || say "Point your HTTPS proxy for $PUBLIC_HOST at http://127.0.0.1:$PORT and keep the Host header."
[ -z "$DOMAIN" ] || say "Make sure your firewall lets ports 80 and 443 in, so Caddy can get a certificate."
say ""
if [ -n "$SETUP" ]; then
  say "$SETUP"
  say "After your account, it connects your Tazmu subscription and signs in your AI tools."
  say "Lost the link? From $DIR, run: $SETUP_LINK_COMMAND"
else
  say "Next, from $DIR:"
  say "  docker compose exec omb codex login --device-auth   # or: claude"
  say "  docker compose exec omb node dist-server/tazmu.js pair"
fi
say "Update later with: sh update.sh"
