#!/usr/bin/env bash
set -euo pipefail

project_directory="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
toolchain="$project_directory/.chasing-mastery/toolchain"

case "$(uname -s):$(uname -m)" in
  Linux:x86_64|Linux:amd64) platform="linux-x86_64" ;;
  Darwin:arm64) platform="darwin-arm64" ;;
  *)
    echo '{"status":"unsupported_host","message":"Connector authoring supports Linux x86-64 and Apple Silicon macOS. Windows and Intel macOS are not yet certified."}' >&2
    exit 1
    ;;
esac

lab="$toolchain/$platform/cm-station-connector-lab"
sandbox="$toolchain/$platform/cm-station-sandbox"
debug_connector="$project_directory/target/debug/cm-station-authored-connector"
release_connector="$project_directory/target/release/cm-station-authored-connector"
action="${1:-status}"

case "$action" in
  status)
    exec "$lab" status --project "$project_directory"
    ;;
  build)
    cargo build --locked --manifest-path "$project_directory/Cargo.toml"
    ;;
  dev)
    cargo build --locked --manifest-path "$project_directory/Cargo.toml"
    scenario="${2:-}"
    if [[ -z "$scenario" ]]; then
      scenario="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["scenarios"][0]["id"])' "$project_directory/chasing-mastery.connector.json")"
    fi
    arguments=(run --project "$project_directory" --executable "$debug_connector" --sandbox "$sandbox" --scenario "$scenario" --output "$project_directory/artifacts/$scenario.json")
    if [[ -n "${3:-}" ]]; then
      arguments+=(--workbench-url "$3")
    fi
    exec "$lab" "${arguments[@]}"
    ;;
  test)
    cargo test --locked --manifest-path "$project_directory/Cargo.toml"
    cargo build --locked --manifest-path "$project_directory/Cargo.toml"
    exec "$lab" ready --project "$project_directory" --executable "$debug_connector" --sandbox "$sandbox" --output "$project_directory/artifacts/verification"
    ;;
  ready)
    cargo test --locked --manifest-path "$project_directory/Cargo.toml"
    cargo build --release --locked --manifest-path "$project_directory/Cargo.toml"
    exec "$lab" ready --project "$project_directory" --executable "$release_connector" --sandbox "$sandbox" --output "$project_directory/dist/review"
    ;;
  *)
    echo '{"status":"invalid_action","message":"Use status, build, dev, test, or ready."}' >&2
    exit 2
    ;;
esac
