#!/bin/bash
# Helper script for cockpits to request services
# Mount this into cockpits at /usr/local/bin/cockpit-service
#
# Usage:
#   cockpit-service start <service>
#   cockpit-service stop <service>
#   cockpit-service status
#   cockpit-service list

REQUESTS_DIR="/var/cockpit/service_requests"
PROJECT="${PROJECT:-$(basename $(dirname /workspace))}"  # Detect from workspace

# Try to get project from workspace mount
if [ -d "/workspace" ]; then
    # /workspace is typically mounted from /home/<project>
    # Read from env or use parent dir name
    PROJECT="${COCKPIT_PROJECT:-unknown}"
fi

# Ensure project dir exists
mkdir -p "$REQUESTS_DIR/$PROJECT"

action="$1"
service="$2"

if [ -z "$action" ]; then
    echo "Usage: cockpit-service <start|stop|status|list> [service]"
    echo "  cockpit-service start backend"
    echo "  cockpit-service stop backend"
    echo "  cockpit-service status"
    echo "  cockpit-service list"
    exit 1
fi

request_id="${action}-${service:-all}-$(date +%s)"
request_file="$REQUESTS_DIR/$PROJECT/${request_id}.request"
response_file="$REQUESTS_DIR/$PROJECT/${request_id}.response"

# Write request
echo "{\"action\":\"$action\",\"service\":\"$service\"}" > "$request_file"
echo "Request submitted: $request_id"

# Wait for response (max 30s)
for i in $(seq 1 30); do
    if [ -f "$response_file" ]; then
        echo "Response:"
        cat "$response_file"
        rm -f "$response_file"
        exit 0
    fi
    sleep 1
done

echo "Timeout waiting for response"
exit 1
