#!/bin/bash
# Wrapper script that SSHes into the ephemeral E2E VM and runs the test script.
# Called from Drone CI to avoid ash/sh quoting issues.
#
# Usage: bash scripts/run-e2e.sh <VM_IP> <API_URL> <REPO_URL> <COMMIT_SHA> <VM_PASSWORD>

set -euo pipefail

VM_IP="$1"
API_URL="$2"
REPO_URL="$3"
COMMIT_SHA="$4"
export SSHPASS="$5"

echo "VM_IP=$VM_IP API_URL=$API_URL"
echo "Waiting for VM to be reachable..."
timeout 60 bash -c "until sshpass -e ssh debian@$VM_IP echo ok 2>/dev/null; do sleep 5; done"

echo "VM reachable. Copying test script..."
sshpass -e scp scripts/e2e-test.sh debian@$VM_IP:/tmp/e2e-test.sh
sshpass -e ssh debian@$VM_IP chmod +x /tmp/e2e-test.sh

echo "Running E2E tests..."
sshpass -e ssh debian@$VM_IP "REPO_URL=$REPO_URL COMMIT_SHA=$COMMIT_SHA API_URL=$API_URL bash /tmp/e2e-test.sh"

echo "Fetching results..."
sshpass -e scp debian@$VM_IP:/tmp/e2e-results.txt /tmp/e2e-results.txt 2>/dev/null || echo "No results file found (tests may not have run)"
