#!/bin/bash

if ! grep -q "/ai_ps/ppimg.py" /etc/supervisor/supervisord.conf; then
    echo "ppis not configured in supervisord.conf."
    exit 0
fi

exit 0

# 检查服务是否正常运行
STATUS=$(/usr/local/bin/supervisorctl status pp | awk '{print $2}')
if [ "$STATUS" != "RUNNING" ]; then
    # 如果服务没有运行则启动它
    echo "supervisorctl pp not running, status is $STATUS then start !"
    /usr/local/bin/supervisorctl start pp

    #检查super状态
    status_output=$(/usr/local/bin/supervisorctl status)
    # 检查是否包含错误提示
    if echo "$status_output" | grep -q "Exited too quickly"; then
        echo "Error: supervisorctl status failed. shutdown supervisorctl..."
        kill -9 $(ps -ef | awk '/ai_ps\/matting/{print $2}')
        /usr/local/bin/supervisorctl shutdown 
        /usr/local/bin/supervisord -c /etc/supervisor/supervisord.conf
    fi

    if echo "$status_output" | grep -q "unix:///tmp/supervisor.sock"; then
        echo "Error: supervisorctl status failed. Starting supervisord..."
        /usr/local/bin/supervisord -c /etc/supervisor/supervisord.conf
    fi

    exit 0
fi

# 设置服务地址
SERVICE_URL="http://127.0.0.1:8903/face"

# 发送HEAD请求，并检查响应状态码
STATUS_CODE=$(curl --head --silent --connect-timeout 10 -m 2 --output /dev/null --write-out '%{http_code}' $SERVICE_URL)

# 检查响应状态码
if [ $STATUS_CODE -eq 200 ]; then
    echo "HEAD $SERVICE_URL and httpCode is 200, Service is running."
else
    echo "Service is not running. Starting..."
    # 尝试重启 pp
    /usr/local/bin/supervisorctl restart pp
fi