#!/bin/bash
# Vox one-line installer:
#   curl -fsSL https://automatescale.com/vox/install | bash
# Bootstraps git/Homebrew if needed, clones (or updates) the repo, and runs
# the full installer. Safe to re-run anytime.
#
# Everything lives inside main() so a partially-downloaded script can never
# execute half an install.
set -e

main() {

  echo "==> Vox bootstrap"

  # Xcode Command Line Tools provide git on a fresh Mac
  if ! xcode-select -p >/dev/null 2>&1; then
    echo "    git needs Apple's Command Line Tools — a dialog will open."
    echo "    Click Install, wait for it to finish, then re-run this command."
    xcode-select --install 2>/dev/null || true
    exit 1
  fi

  # Homebrew (interactive — reads your password from the terminal)
  if ! command -v brew >/dev/null 2>&1 && [ ! -x /opt/homebrew/bin/brew ] && [ ! -x /usr/local/bin/brew ]; then
    echo "    Homebrew not found — installing it first (you'll be asked for your password)..."
    if ( : </dev/tty ) 2>/dev/null; then
      /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" </dev/tty
    else
      NONINTERACTIVE=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    fi
  fi

  cd "$HOME"
  if [ -d "$HOME/vox/.git" ]; then
    echo "==> Existing install found — updating..."
    git -C "$HOME/vox" pull --ff-only || {
      RESCUE="rescue-$(date +%Y%m%d-%H%M%S)"
      git -C "$HOME/vox" branch "$RESCUE" >/dev/null 2>&1 && \
        echo "    local changes preserved on branch: $RESCUE (git log $RESCUE to inspect)"
      echo "    local copy diverged — resetting to latest release..."
      git -C "$HOME/vox" fetch origin && git -C "$HOME/vox" reset --hard origin/main
    }
  else
    echo "==> Cloning Vox..."
    rm -rf "$HOME/vox"
    git clone https://github.com/AutomateScale/vox.git "$HOME/vox"
  fi

  cd "$HOME/vox"
  if ( : </dev/tty ) 2>/dev/null; then
    exec bash install.sh </dev/tty
  else
    exec bash install.sh          # headless/agent install: no TTY to attach
  fi
}

main "$@"
