#!/usr/bin/env bash
# Sync project to Pi, ensure venv + per-test requirements, run main.py with TTY.
#
# Usage: bin/deploy <test-dir>
# Example: bin/deploy tests/02-wakeword

set -euo pipefail

PI_USER="${PI_USER:-pi}"
PI_HOST="${PI_HOST:-192.168.50.115}"
PI_PASS="${PI_PASS:-assistant}"
PI_PATH="${PI_PATH:-/home/$PI_USER/assistant}"

TEST_DIR="${1:?usage: bin/deploy <test-dir>}"
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

if [ ! -f "$PROJECT_ROOT/$TEST_DIR/main.py" ]; then
  echo "no main.py at $PROJECT_ROOT/$TEST_DIR" >&2
  exit 1
fi

REDACT() { sed -E "s/${PI_PASS}/***/g"; }

echo "==> sync $PROJECT_ROOT -> $PI_USER@$PI_HOST:$PI_PATH"
sshpass -p "$PI_PASS" rsync -az --delete \
  -e "ssh -o StrictHostKeyChecking=accept-new" \
  --exclude='.git/' --exclude='.venv/' --exclude='__pycache__/' \
  --exclude='*.wav' --exclude='.openwakeword-cache/' \
  "$PROJECT_ROOT/" "$PI_USER@$PI_HOST:$PI_PATH/" 2>&1 | REDACT

echo "==> venv + pip install $TEST_DIR/requirements.txt"
sshpass -p "$PI_PASS" ssh -o StrictHostKeyChecking=accept-new \
  "$PI_USER@$PI_HOST" \
  "set -e
   cd '$PI_PATH'
   [ -d .venv ] || python3 -m venv .venv
   .venv/bin/pip install --upgrade pip -q
   .venv/bin/pip install -q -r '$TEST_DIR/requirements.txt'
   if [ -f '$TEST_DIR/requirements-nodeps.txt' ]; then
     .venv/bin/pip install -q --no-deps -r '$TEST_DIR/requirements-nodeps.txt'
   fi" 2>&1 | REDACT

echo "==> run $TEST_DIR/main.py"
sshpass -p "$PI_PASS" ssh -t -o StrictHostKeyChecking=accept-new \
  "$PI_USER@$PI_HOST" \
  "cd '$PI_PATH/$TEST_DIR' && '$PI_PATH/.venv/bin/python' main.py" 2>&1 | REDACT
