#!/bin/bash

source .env

# pid=$(ps -ef | grep BenBot | grep -v grep | awk '{print $2}')
pid=$(pidof $WHICHBOT)

case "$1" in

    nohup)
        if [ $pid ]; then
            echo "starting BenBot in background (nohup)"
            nohup php run.php $WHICHBOT > bot.out 2> bot.err < /dev/null &
        else
            echo "BenBot already running"
        fi
        ;;

    start)
        if [ $pid ]; then
            kill $pid
        fi
        php run.php
        ;;

    stop)
        if [ $pid ]; then
            echo "killing BenBot ($pid)"
            kill $pid
        fi
        ;;

    status)
        #pgrep BenBot && echo "Running"
        if [ $pid ]; then
            echo "BenBot running with pid $pid"
        else
            echo "BenBot not running"
        fi
        ;;

	log)
	    if [ $pid ]; then
		less bot.out
	    else
		echo "BenBot not running"
	    fi
	    ;;

    check)
        find ./src -name \*.php -exec php -l "{}" \;
        php -l *.php
        ;;

    loc)
        find src -name '*.php' | xargs wc -l
        ;;

    cloc)
        cloc --exclude-dir=vendor --by-file-by-lang .
        ;;

    sync)
        rsync -av ben@benharris.ch:workspace/benbot/uploaded_images/ uploaded_images/
	rsync -av ben@benharris.ch:workspace/benbot/bot_data/ bot_data/

        ;;

    restart)
        if [ $pid ]; then
            echo "killing BenBot ($pid)"
            kill $pid
        fi
        echo "starting BenBot in background (nohup)"
        nohup php run.php $WHICHBOT > bot.out 2> bot.err < /dev/null &
        ;;


    *)
        echo $"Usage: $0 {start|nohup|stop|restart|log|status}"
        exit 1

esac
