#!/bin/sh
# Supervisord event listener for docker_server deployments
# Listens for PROCESS_STATE_FATAL and PROCESS_STATE_EXITED events
# Kills supervisord (PID 1) when model-server crashes

echo "Event listener started, waiting for events..." >&2
echo "READY"

while IFS= read -r line; do
    echo "Event listener received line: [$line] (length: ${#line})" >&2
    
    # Check if this is a blank line (end of headers, start of payload)
    if [ -z "$line" ]; then
        echo "Blank line detected, reading payload..." >&2
        # Read the payload
        if IFS= read -r payload; then
            echo "Event listener received payload: [$payload]" >&2
            
            # Check if this is a model-server event
            if echo "$payload" | grep -q "^model-server:"; then
                echo "Model-server event detected, killing supervisord..." >&2
                kill -15 1
                exit 0
            fi
            
            # Acknowledge the event
            echo "RESULT 2"
            echo "OK"
        else
            echo "Failed to read payload" >&2
            break
        fi
    else
        echo "Non-blank line (header): $line" >&2
        # Continue loop to read next line (blank line or more headers)
    fi
done

echo "Event listener loop exited" >&2

