#!/bin/bash
#
# Purpose : Run the smoketest scenarios, each in a fresh macOS VM, with Tart
#           on an Apple silicon Mac. See README.md.
#
# Usage: smoketest/run [--image REF] [--tier quick|all] [--keep] [scenario...]
#        smoketest/run --list
#
# Runs with the bash macOS comes with (3.2).

# Wrapped in { ...; exit; } so bash reads the whole script up front
{

SMOKETEST="$(cd "$(dirname "$0")" && pwd)"
REPO="$(dirname "$SMOKETEST")"
IMAGE="ghcr.io/cirruslabs/macos-tahoe-vanilla:latest"
TIER=quick
KEEP=0
SCENARIOS=()
# The vanilla images' user; it has passwordless sudo and logs in by itself
VM_USER="admin"
VM_PASSWORD="admin"

usage() {
  cat << EOF
Usage: smoketest/run [options] [scenario...]

  --image REF        Tart image to clone (default: $IMAGE)
  --tier quick|all   quick leaves out the slow scenarios (default: quick)
  --keep             Leave each VM running afterwards, to look around in it
  --list             List the scenarios and their tier

Scenarios are named by file name or number, e.g. 60-backup or 60.
EOF
}

scenario_var() {
  sed -nE "s/^$2=\"?([^\"]*)\"?.*/\\1/p" "$1" | head -n 1
}

list() {
  local file
  for file in "$SMOKETEST"/scenarios/*.sh; do
    printf '%-20s %-6s %s\n' "$(basename "$file" .sh)" "$(scenario_var "$file" TIER)" \
      "$(scenario_var "$file" DESCRIPTION)"
  done
}

while [ $# -gt 0 ]; do
  case "$1" in
    --image) IMAGE="$2"; shift 2 ;;
    --tier) TIER="$2"; shift 2 ;;
    --keep) KEEP=1; shift ;;
    --list) list; exit 0 ;;
    -h|--help) usage; exit 0 ;;
    -*) usage; exit 2 ;;
    *) SCENARIOS+=("$1"); shift ;;
  esac
done

if [ "$(uname -s)" != Darwin ] || [ "$(uname -m)" != arm64 ]; then
  echo "Tart runs macOS VMs on Apple silicon Macs only."
  exit 1
fi
command -v tart > /dev/null || { echo "Tart isn't installed: brew install cirruslabs/cli/tart"; exit 1; }

# The scenario files to run
pick() {
  local file name want
  for file in "$SMOKETEST"/scenarios/*.sh; do
    name="$(basename "$file" .sh)"
    if [ ${#SCENARIOS[@]} -eq 0 ]; then
      [ "$TIER" = all ] || [ "$(scenario_var "$file" TIER)" = quick ] || continue
      echo "$file"
    else
      for want in "${SCENARIOS[@]}"; do
        case "$name" in "$want"|"$want"-*) echo "$file" ;; esac
      done
    fi
  done
}

RESULTS="$SMOKETEST/results/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$RESULTS"
KEY="$RESULTS/id_ed25519"
ssh-keygen -q -t ed25519 -N '' -f "$KEY" || exit 1

# Answers ssh's password question once, to put the key in the VM
ASKPASS="$RESULTS/askpass"
printf '#!/bin/sh\necho %s\n' "$VM_PASSWORD" > "$ASKPASS"
chmod 700 "$ASKPASS"

SSH_OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR
  -o ConnectTimeout=5 -o ServerAliveInterval=15)

vm_ssh() {
  ssh "${SSH_OPTS[@]}" -i "$KEY" -o BatchMode=yes "$VM_USER@$IP" "$@"
}

# Clone the image, start it and wait until ssh with the key works
vm_start() {
  local name="$1" i
  echo "  Cloning $IMAGE (the first time downloads it, about 25 GB)..."
  tart clone "$IMAGE" "$name" || return 1
  tart run --no-graphics "$name" > "$RESULTS/$name.tart.log" 2>&1 &
  IP="$(tart ip --wait 180 "$name")" || { echo "  The VM didn't get an address."; return 1; }
  for i in $(seq 1 60); do
    SSH_ASKPASS="$ASKPASS" SSH_ASKPASS_REQUIRE=force DISPLAY=none \
      ssh "${SSH_OPTS[@]}" -o PubkeyAuthentication=no "$VM_USER@$IP" \
      'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys' \
      < "$KEY.pub" 2> /dev/null && break
    sleep 5
  done
  vm_ssh true || { echo "  Couldn't ssh to the VM at $IP."; return 1; }
  # The VM logs in by itself; wait for its desktop session, which the
  # scenarios run in
  for i in $(seq 1 60); do
    vm_ssh 'pgrep -x Dock > /dev/null' && return 0
    sleep 5
  done
  echo "  The VM's desktop session didn't start."
  return 1
}

# The working copy, as it is now, to ~/connector in the VM
vm_copy() {
  COPYFILE_DISABLE=1 tar -C "$REPO" --exclude ./.claude --exclude ./smoketest/results \
    --exclude ./.git -czf - . | vm_ssh 'rm -rf ~/connector && mkdir ~/connector && tar -xzf - -C ~/connector'
}

# Run in the desktop session (launchctl asuser), as macOS' GUI pieces
# (open, launchd's gui domain, Gatekeeper, the keychain) expect, rather than
# in ssh's own session
vm_scenario() {
  vm_ssh "sudo launchctl asuser \$(id -u) sudo -u $VM_USER -H /bin/bash ~/connector/smoketest/lib/runner.sh ~/connector/smoketest/scenarios/$1"
}

vm_stop() {
  local name="$1"
  if [ $KEEP -eq 1 ]; then
    echo "  Kept $name running at $IP (ssh -i \"$KEY\" $VM_USER@$IP). Afterwards: tart stop $name; tart delete $name"
    return 0
  fi
  tart stop "$name" > /dev/null 2>&1
  tart delete "$name" > /dev/null 2>&1
}

PASSED=() FAILED=()
FILES=()
while IFS= read -r file; do
  FILES+=("$file")
done < <(pick)
if [ ${#FILES[@]} -eq 0 ]; then
  echo "No scenarios to run. smoketest/run --list shows them."
  exit 2
fi

for file in "${FILES[@]}"; do
  scenario="$(basename "$file" .sh)"
  name="connector-smoke-$scenario-$$"
  log="$RESULTS/$scenario.log"
  echo
  echo "== $scenario: $(scenario_var "$file" DESCRIPTION)"
  if vm_start "$name" && vm_copy; then
    vm_scenario "$(basename "$file")" 2>&1 | tee "$log"
    status=${PIPESTATUS[0]}
  else
    status=1
    echo "  The VM didn't start; see $RESULTS/$name.tart.log" | tee "$log"
  fi
  vm_stop "$name"
  if [ "$status" -eq 0 ]; then PASSED+=("$scenario"); else FAILED+=("$scenario"); fi
done

echo
echo "Passed: ${PASSED[*]:-none}"
echo "Failed: ${FAILED[*]:-none}"
echo "Logs: $RESULTS"
[ ${#FAILED[@]} -eq 0 ]
exit
}
