#!/usr/bin/env bash

# @(#) basic CLI utility script for gunicorn

# TODO may be replaced by setting gunicorn up as a service

start() {
    if [ $(id -un) == 'www-data' ]
    then
        if cd /var/www/reporter.apache.org/scripts
        then
            pwd
            if gunicorn3 -b 127.0.0.1 -w 6 -D wsgi:app
            then
                echo "Started gunicorn"
            fi
        fi
    else
        echo "You must run this as www-data"
    fi
}

wait() {
    echo "Waiting for gunicorn to stop ..."
    while pgrep -o -f "gunicorn3.*wsgi:app"
    do
        sleep 1
    done
    echo "... stopped"
}

stop(){
    if [ $(id -un) == 'www-data' ]
    then
        PID=$(pgrep -o -f "gunicorn3.*wsgi:app")
        if [ -z "$PID" ]
        then
            echo "Cannot find gunicorn pid"
        else
            kill $PID
        fi
    else
        echo "You must run this as www-data"
    fi
}

reload(){
    if [ $(id -un) == 'www-data' ]
    then
        pkill -HUP -f gunicorn3
    else
        echo "You must run this as www-data"
    fi
}

# allow multiple commands in sequence, e.g. stop status wait

for cmd
do
    case "$cmd" in
        reload)
            reload
        ;;
        stop)
            stop
        ;;
        wait)
            wait
        ;;
        start)
            start
        ;;
        restart)
            stop
            wait
            start
        ;;
        status) # show details of processes
            PSOUT=$(ps -eo pid,ppid,ruser,lstart,cmd)
            # run grep as a separate command to avoid matching itself
            echo "$PSOUT" | grep "gunicorn3\|STARTED"
        ;;
        ppid) # oldest pid is the parent
            pgrep -o -f "gunicorn3.*wsgi:app"
        ;;
        *)
            echo "Command '$cmd' not recognised: reload, stop, restart, start, status, ppid"
        ;;
    esac
done
