#!/usr/bin/env bash
# Builds the OpenTAP image and runs the smoke-test plan.
# Run from the folder that holds the Dockerfile, plans/ and Settings/.
# Usage: ./smoke-test.sh [image-tag]
set -euo pipefail

TAG="${1:-opentap-smoke:test}"
PLATFORM_ARGS=()
# On Apple silicon, the Dockerfile's x64 OpenTAP build needs amd64 emulation.
if [[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]]; then
  PLATFORM_ARGS=(--platform linux/amd64)
fi

mkdir -p Settings logs   # Dockerfile COPYs Settings/; logs/ receives session logs

echo "== 1. Build image"
docker build "${PLATFORM_ARGS[@]}" -t "$TAG" .

echo "== 2. Check OpenTAP inside the image"
docker run --rm "${PLATFORM_ARGS[@]}" --entrypoint tap "$TAG" package list --installed

echo "== 3. Run the smoke-test plan"
set +e
docker run --rm "${PLATFORM_ARGS[@]}" \
  -v "$PWD/logs:/opt/tap/SessionLogs" \
  "$TAG" plans/MyPlan.TapPlan --non-interactive 2>&1 | tee logs/console.txt
RC=${PIPESTATUS[0]}
set -e

echo "== 4. Verify"
if [[ $RC -ne 0 ]]; then
  echo "FAIL: tap run exited with code $RC"; exit 1
fi
if ! grep -q "SMOKE-TEST-OK" logs/console.txt; then
  echo "FAIL: marker line not found in output"; exit 1
fi
echo "PASS: image builds, OpenTAP runs, plan completes (session logs in ./logs)"
