#!/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 true; do
    # Read header line
    IFS= read -r line || {
        echo "Read failed or EOF, exiting loop" >&2
        break
    }
    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
        IFS= read -r payload || {
            echo "Failed to read payload" >&2
            break
        }
        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 "Non-blank line (header): $line" >&2
    fi
done

echo "Event listener loop exited" >&2

