#!/bin/bash

CONF=/usr/conf


start_cloud()
{
    /sbin/start-stop-daemon -S \
        -x /usr/local/bin/cloud-api \
        -m -p $CONF/run/cloud-api.pid \
        -b
}

stop_cloud() {
    killall cloud-api.php
    rm -f $CONF/run/cloud-api.pid
}


check_runable()
{
    ps ax | grep cloud-api.php | grep -v grep | grep " R " > /dev/null 
}

cloud-check-cpu()
{
    while ( true ) ; do 
        if check_runable ; then
            echo "cloud-api runable"
            for i in $(seq 1 10) ; do
                    if ! check_runable ; then
                        break;
                    fi
                    sleep 1;
            done
            if [ "$i" = "10" ] ; then
                echo "restarting cloud-api"
                stop_cloud
                sleep 1
                start_cloud
            fi
        fi
        sleep 60;
    done
}


#cloud-check-cpu &

case "$1" in
	start)
            start_cloud
            ;;
            stop)
                stop_cloud
                killall -9 S60cloud
                ;;
	restart)
                stop_cloud
                start_cloud
		;;
	*)
		echo "Usage: $0 {start|stop|restart}" >&2
		exit 1
		;;
esac

