#!/usr/bin/env bash
# Capstone 4, observability: logs -> metrics -> traces -> OpenTelemetry -> dashboards -> alerts -> profiling.
# The orders service runs locally (port 18084) and sends spans over OTLP; Prometheus (19090),
# Grafana (13000), and an OpenTelemetry Collector (14318) run as containers on the host network.
source "$(dirname "$0")/../lib.sh"
need docker curl jq python3
work obs
for p in 18084 19090 13000 14318; do port_free "$p"; done
cp -r "$(dirname "$0")/conf" "$APP_SRC/orders.py" "$WORK/"
cd "$WORK"

say "1. Start the OpenTelemetry Collector, Prometheus (with alert rules), and Grafana (provisioned)"
docker run -d --name cap-otel --network host -v "$WORK/conf/otel-collector.yaml:/etc/otelcol/config.yaml:ro" \
  otel/opentelemetry-collector:0.115.1 > /dev/null
docker run -d --name cap-prom --network host -v "$WORK/conf/prometheus.yml:/etc/prometheus/prometheus.yml:ro" \
  -v "$WORK/conf/alerts.yml:/etc/prometheus/alerts.yml:ro" prom/prometheus:v2.55.1 \
  --config.file=/etc/prometheus/prometheus.yml --web.listen-address=127.0.0.1:19090 > /dev/null
docker run -d --name cap-graf --network host -e GF_SERVER_HTTP_PORT=13000 -e GF_SERVER_HTTP_ADDR=127.0.0.1 \
  -e GF_AUTH_ANONYMOUS_ENABLED=true -e GF_AUTH_ANONYMOUS_ORG_ROLE=Viewer -e GF_SECURITY_ADMIN_PASSWORD=capstone-only \
  -v "$WORK/conf/grafana:/etc/grafana/provisioning:ro" grafana/grafana:11.3.0 > /dev/null
wait_for http://127.0.0.1:19090/-/ready 60 && echo "  Prometheus ready"
wait_for http://127.0.0.1:13000/api/health 90 && echo "  Grafana ready"

say "2. Start orders with tracing on, and send traffic"
PORT=18084 VERSION=1.0.0 OTLP_URL=http://127.0.0.1:14318/v1/traces nohup python3 orders.py > service.log 2>&1 &
echo $! > service.pid
wait_for http://127.0.0.1:18084/readyz 20
for i in $(seq 120); do curl -s -o /dev/null http://127.0.0.1:18084/orders; done
curl -s -o /dev/null -H "traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" http://127.0.0.1:18084/orders
echo "  121 requests sent (one with a known trace ID)"
