#!/usr/bin/env bash
#

###################################################################
# Runs a sanity check against local control to ensure it is up
# and running before we go to the trouble of building and
# running the tests
#
# Usage: api-sanity-checks.sh
#
# Returns 0 on success

SCRIPT_DIR=$(dirname "$(realpath "$0")")

# Use GitHub Actions log grouping when running in CI; plain headers locally.
begin_section() {
    if [ "$GITHUB_ACTIONS" = "true" ]; then
        echo "::group::$1"
    else
        echo ""
        echo "=== $1 ==="
    fi
}
end_section() { [ "$GITHUB_ACTIONS" = "true" ] && echo "::endgroup::"; :; }

# Path to the api key JSON file
FILE="$SCRIPT_DIR/apple-integration-testing-control-api-key.json"

begin_section "Control API Sanity Checks"

# Wait for control to populate the fake devices.
sleep 5

if [ ! -f "$FILE" ]; then
    echo "[FAILURE] API key file not found: $FILE. devcontrol likely failed to start. Check logs." >&2
    end_section
    exit 1
fi

CONTROL_API_KEY=$(jq -r '.apiKey' "$FILE")
if [ -z "$CONTROL_API_KEY" ]; then
    echo "[FAILURE] Could not read API key from $FILE." >&2
    end_section
    exit 1
fi

RESPONSE=$(curl -s \
                --max-time 5 \
                "http://localhost:31544/api/v2/tailnet/mobileme.com/devices" \
                -u "${CONTROL_API_KEY}:")

if [ -z "$RESPONSE" ]; then
    echo "[FAILURE] No response from control API." >&2
    end_section
    exit 1
fi

DEVICE_COUNT=$(echo "$RESPONSE" | jq '.devices | length')
if [ "$DEVICE_COUNT" -ge 15 ]; then
    echo "[  OK  ] Control is alive ($DEVICE_COUNT devices)."
    end_section
else
    echo "[FAILURE] Expected >=15 devices from control API, got $DEVICE_COUNT." >&2
    end_section
    exit 1
fi
