#!/bin/bash
export LANG=ru_RU.UTF-8

USER=$(whoami)
GUNICORN_USER=$USER
CURDIR=$(pwd)


# defaults
LOGCONFIG=""
PRELOAD=""
WORKER_TIMEOUT=""
WORKER_CLASS=""
ACCESS_LOGFILE=""
ACCESS_LOGFORMAT=""

WORKERS=1
MAXREQUESTS=100

NAME=yandex-avia-api-$USER

APP=wsgi
APPDIR=$CURDIR
GUNICORN_CONF=$APPDIR/gunicorn_conf.py
ADDRESS=unix:/tmp/avia_api.sock
PIDFILE=$APPDIR/gunicorn.pid
LOGFILE=$APPDIR/log/gunicorn.log
LOGLEVEL="DEBUG"
PYTHON_PATH=""

if [ "$LOGFILE" ]
then
    LOGDIR=`dirname $LOGFILE`
    if [ -n $LOGDIR ]; then
        if [ ! -d $LOGDIR ]; then
            mkdir -p $LOGDIR
        fi
    fi
    touch $LOGFILE
fi

GUNICORN_OPTIONS="--daemon --bind=$ADDRESS --pid=$PIDFILE --workers=$WORKERS "
GUNICORN_OPTIONS="$GUNICORN_OPTIONS --log-file=$LOGFILE "
GUNICORN_OPTIONS="$GUNICORN_OPTIONS --log-level=$LOGLEVEL "
GUNICORN_OPTIONS="$GUNICORN_OPTIONS --max-requests=$MAXREQUESTS "

if [ "$GUNICORN_CONF" ]
then
    GUNICORN_OPTIONS="$GUNICORN_OPTIONS --config=$GUNICORN_CONF "
fi


# set -x


detect_pid()
{
    PIDFILE=$1
    if [ -s $PIDFILE ]
    then
        #echo "PID from pidfile:  "`cat $PIDFILE`
        PID=`cat $PIDFILE`
        echo $PID
    else
        #echo "Pidfile not found, trying to find pid"
        ALLGUNIPIDS=`pgrep -P 1 gunicorn | tr '\n' '|' | sed  's/|$//'`
        if [ $ALLGUNIPIDS ]
        then
            PID=`ps ax | egrep  $ALLGUNIPIDS | grep -v grep | grep $PIDFILE | awk '{print $1}'`
            if [ $PID ]
            then
                #echo "PID from ps: $MbPID"
                #echo $PID > $PIDFILE
                echo $PID
                exit 0
            else
                #echo "Failed to find pid, exit 1"
                exit 1
            fi
        else
            #echo "Failed to find pid, exit 1"
            exit 1
        fi
    fi
    #echo "in detect $PID"
    #return $PID
}


start()
{
    echo "Starting Gunicorn Application: "
    echo $NAME

    if start-stop-daemon --quiet --stop --signal 0 --pidfile $PIDFILE 2>/dev/null 1>/dev/null; then
        echo "Aready running."
        exit 0
    fi

    PYTHONPATH=$APPDIR:$PYTHON_PATH start-stop-daemon \
        --start \
        --quiet \
        --pidfile $PIDFILE \
        -c $GUNICORN_USER \
    --exec /usr/bin/gunicorn $APP -- $GUNICORN_OPTIONS \
    || echo -n " already running"

    echo "Starting $NAME done"
}


stop()
{
    echo "Stopping GunicornApplication: "
    echo $NAME

    PID=$(detect_pid $PIDFILE)
    echo "pid from detect: $PID"

    if [ $PID ]
    then
        #echo "Pid found"
        echo $PID > $PIDFILE
        #Get child pids before parent vanished
        CHILDS_PIDLIST=`pgrep -P $PID`;

        #Kill gunicorn application
        start-stop-daemon --quiet --stop --signal 0 --retry=TERM/10/KILL/5  --pidfile $PIDFILE 2>&1 >/dev/null
        if pgrep $PID
        then
            kill -9 $PID
        fi

        #Kill childs if any
        for i in $CHILDS_PIDLIST
        do
            if ps aufx | grep $i | grep -v grep>/dev/null
                then kill -9 $i
            fi
        done

        echo "Stopping $NAME done"
    else
        echo "Failed to find pid"
        exit 0
    fi

    RETVAL=1
    echo ""
}


case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        $0 stop $@
        sleep 5
        $0 start $@
        RETVAL=$?
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}" >&2
        exit 1
        ;;
esac
