#!/bin/bash

# Terminalwire v2 installer. You opted into v2 with a channel in the URL:
#
#   curl -sSL https://tinyzap.terminalwire.sh/stable | bash
#
# (Programmatic equivalent: curl -sSL https://tinyzap.terminalwire.sh -H "X-Version: 2.0" -H "X-Channel: stable" | bash)
#
# It will:
#   1. Detect your operating system and architecture.
#   2. Download the v2 Terminalwire CLI for those specs.
#   3. Install it under ~/.terminalwire (or $TERMINALWIRE_HOME) and put it on PATH.
#   4. Install the tinyzap application.
#
# Read the code below before running it. For more info: https://terminalwire.com.

set -euo pipefail

ARCH=$(uname -m)
OS=$(uname -s)
TERMINALWIRE_HOME="${TERMINALWIRE_HOME:-$HOME/.terminalwire}"
BIN="$TERMINALWIRE_HOME/bin"
URL="https://tinyzap.terminalwire.sh/bash/v2/builds"

# Download with curl or wget, telling the build server our arch/os via headers.
get(){
  if command -v curl >/dev/null 2>&1; then
    curl --progress-bar --fail-with-body -L \
      -H "X-Arch: $ARCH" \
      -H "X-OS: $OS" \
      -H "X-Channel: stable" \
      "$1"
  elif command -v wget >/dev/null 2>&1; then
    wget --quiet --show-progress -O - \
      --header="X-Arch: $ARCH" \
      --header="X-OS: $OS" \
      --header="X-Channel: stable" \
      "$1" || exit 1
  else
    echo "Error: neither curl nor wget is available on this system." >&2
    exit 1
  fi
}

echo "Installing Terminalwire v2 for $OS/$ARCH into $TERMINALWIRE_HOME"
mkdir -p "$BIN"

# The tarball is the ONE binary (terminalwire-exec) plus two constant files it
# resolves: terminalwire-policy (a symlink to it) and terminalwire (a stub pointing
# at the management server). An update is a single atomic swap of terminalwire-exec.
get "$URL" | tar -xz -C "$BIN"

# Bootstrap runs through the engine binary directly (the `terminalwire` command is a
# stub now, not a CLI): put bin on PATH + pin the channel, then drop the app launcher.
"$BIN/terminalwire-exec" setup --shell "$SHELL" --channel stable
# (The terminalwire.com management grant is baked into the engine now — no seeded
# policy file. It's scoped to ~/.terminalwire/usr/bin and can't reach the engine or
# control files. Change it only by shipping a new client.)
"$BIN/terminalwire-exec" install tinyzap https://tinyzap.com/terminal

echo
echo "Installed. Restart your shell (or source your rc file), then run: tinyzap"
