#!/usr/bin/env bash
# Compile and deploy service binaries via Argo Workflows.
#
# Usage:
#   ./scripts/argo-compile-deploy.sh                      # all services, HEAD
#   ./scripts/argo-compile-deploy.sh --sha abc1234        # specific commit
#   ./scripts/argo-compile-deploy.sh --services "api trading-service"  # subset
#   ./scripts/argo-compile-deploy.sh --webhook            # trigger via webhook
#
# Requires: argo CLI (default) or curl (webhook mode)
set -euo pipefail

SHA="HEAD"
SERVICES=""
WEBHOOK=false
WEBHOOK_URL="http://workflow-trigger-eventsource-svc.foxhunt:12001/compile-deploy"
WATCH=false

usage() {
  cat <<EOF
Usage: $(basename "$0") [OPTIONS]

Options:
  --sha <commit>       Git commit SHA to build (default: HEAD)
  --services <list>    Space-separated service packages to build
                       (default: all 7 services)
  --webhook            Trigger via webhook instead of argo CLI
  --watch              Follow workflow logs after submission
  -h, --help           Show this help
EOF
  exit 0
}

while [[ $# -gt 0 ]]; do
  case $1 in
    --sha)       SHA="$2"; shift 2 ;;
    --services)  SERVICES="$2"; shift 2 ;;
    --webhook)   WEBHOOK=true; shift ;;
    --watch)     WATCH=true; shift ;;
    -h|--help)   usage ;;
    *)           echo "Unknown option: $1"; usage ;;
  esac
done

if $WEBHOOK; then
  echo "Triggering compile-deploy via webhook..."
  PAYLOAD="{\"commit_sha\": \"${SHA}\"}"
  curl -sf -X POST "$WEBHOOK_URL" \
    -H 'Content-Type: application/json' \
    -d "$PAYLOAD"
  echo "Webhook sent: $PAYLOAD"
  exit 0
fi

# Build argo submit command
CMD="argo submit -n foxhunt --from=wftmpl/compile-and-deploy"
CMD="$CMD -p commit-sha=$SHA"

if [[ -n "$SERVICES" ]]; then
  CMD="$CMD -p service-packages=\"$SERVICES\""
fi

if $WATCH; then
  CMD="$CMD --watch"
fi

echo "Submitting compile-and-deploy workflow..."
echo "  commit-sha: $SHA"
[[ -n "$SERVICES" ]] && echo "  services:   $SERVICES" || echo "  services:   all (default)"
echo ""
eval "$CMD"
