﻿
#!/bin/sh

# Init ########################################
DATE=$(date)
SCRIPT="/home/moin/bin/moinmoin"
USER="moin"
SERVER="nginx"
SERVERBIN="/home/moin/bin/nginx"
SERVERPID="/home/moin/var/nginx.pid"
WSGI="uwsgi"
WSGIBIN="/home/moin/bin/uwsgi -x /home/moin/etc/uwsgi.xml"
WSGIPID="/home/moin/var/uwsgi.pid"

# START #######################################
if [ "$1"  == "start" ]; then
        echo "$DATE START $WSGI and $SERVER (info)"
        if ! $SCRIPT check $SERVER; then
                echo "$DATE START $SERVER"
        $SERVERBIN
        fi
        if ! $SCRIPT check $WSGI; then
                echo "$DATE START $WSGI"
        $WSGIBIN > /dev/null 2>&1
        fi

# RESTART #####################################
elif [ "$1" == "restart" ]; then
        echo "$DATE RESTART $WSGI and $SERVER (info)"
        $SCRIPT stop
        $SCRIPT start

# STOP ########################################
elif [ "$1" == "stop" ]; then
    echo "$DATE STOP $WSGI and $SERVER (info)"
    # SERVER ##############
    if [ -f $SERVERPID ]; then
        echo "$DATE STOP $SERVER"
        $SERVERBIN -s quit
        wait
    fi
    if $SCRIPT check $SERVER; then
        echo "$DATE KILL $SERVER!"
        killall -u $USER -9 $SERVER
        wait
        if [ -f $SERVERPID ]; then
            rm $SERVERPID
        fi
    fi

    # WSGI ##############
        if [ -f $WSGIPID ]; then
            echo "$DATE STOP $WSGI"
            kill -s int `cat $WSGIPID`
            wait
            sleep 3
        fi
    if $SCRIPT check $WSGI; then
        echo "$DATE KILL $WSGI!"
        killall -u $USER -9 $WSGI
        wait
        if [ -f $WSGIPID ]; then
                    rm $WSGIPID
        fi
    fi

# RELOAD #####################################
elif [ "$1" == "reload" ]; then
    echo "$DATE RELOAD only $WSGI (info)"
    if $SCRIPT check $WSGI; then
        if [ -f $WSGIPID ]; then
            echo "$DATE RELOAD $WSGI"
            kill -s 1 `cat $WSGIPID`
            wait
        else
            echo "$DATE missing $WSGIPID"
            exit
        fi
    else
        echo "$DATE RELOAD $WSGI NOT possible"
        exit 1
    fi


# CHECK ######################################
elif [ "$1" == "check" ]; then
        if ps u -C $2 | grep -v grep | grep $USER > /dev/null
    then
        echo "$DATE $2 is still running (status)"
                exit 0
        else
                echo "$DATE $2 is NOT running (status)"
                exit 1
        fi

# STATUS ######################################
elif [ "$1" == "status" ]; then
    $SCRIPT check $SERVER
    $SCRIPT check $WSGI

# HELP ########################################
else
        echo "$DATE Script for $SERVER and $WSGI (help)"
        echo "$SCRIPT [start|restart|stop|status|kill]"
        echo "$SCRIPT [check] [server]"
fi

# EXIT ########################################
exit 0
