#!/bin/bash
#
# chkconfig: 345 99 01
# description: healthy

# Service configurations
SERVICE="healthy"
SERVICE_BIN="/etc/nerd4ever/asterisk/bin/healthy"
SERVICE_PID="/var/run/healthy.pid"

# Check service status
status() {
    echo -n "Checking $SERVICE service status... "
    if [ -f $SERVICE_PID ]; then
        pid=$(cat $SERVICE_PID)
        if ps -p $pid > /dev/null; then
            echo "Running (PID $pid)"
            return 0
        else
            echo "Stopped (PID $pid)"
            return 1
        fi
    else
        echo "Stopped (no PID)"
        return 3
    fi
}

# Start the service
start() {
    status
    if [ $? -eq 0 ]; then
        echo "Service is already running"
    else
        echo -n "Starting $SERVICE service... "
        nohup $SERVICE_BIN -c /etc/nerd4ever/asterisk/conf.d/main.json > /dev/null 2>&1 &
        pid=$!
        echo $pid > $SERVICE_PID
        if [ $? -eq 0 ]; then
            echo "OK (PID $pid)"
            return 0
        else
            echo "FAILED"
            return 1
        fi
    fi
}

# Stop the service
stop() {
    status
    if [ $? -eq 0 ]; then
        echo -n "Stopping $SERVICE service... "
        pid=$(cat $SERVICE_PID)
        kill $pid
        if [ $? -eq 0 ]; then
            echo "OK"
            return 0
        else
            echo "FAILED"
            return 1
        fi
    else
        echo "Service is already stopped"
        return 3
    fi
}

# Restart the service
restart() {
    stop
    start
}

# Handle arguments
case "$1" in
    status)
        status
        ;;
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    *)
        echo "Usage: $0 {status|start|stop|restart}"
        exit 1
        ;;
esac
exit 0
