#!/bin/bash

COMMAND=${1:-"state"}
PROGRAM=WMCXmlLimits

WMC_CONFIG=/etc/yandex/webmaster/wmconsole.cfg
XML_CONFIG=/etc/yandex/webmaster/xmlsearch.cfg

if [ -r $XML_CONFIG ]; then
    . $XML_CONFIG
else
    echo "Cannot load config $XML_CONFIG!"
    exit
fi

XML_HOST_DB_URLS=$HOST_DB_URLS

if [ -r $WMC_CONFIG ]; then
    . $WMC_CONFIG
else
    echo "Cannot load config $WMC_CONFIG!"
    exit
fi

export YT_TOKEN=$WMCTOPLOADER_YT_TOKEN

RunLoader() {
    PIDFILE=$WMCXMLLIMITS_HOME/$PROGRAM.pid
    LOGFILE=$WMCXMLLIMITS_HOME/$PROGRAM.log
    CONFIGFILE=$WMCXMLLIMITS_HOME/$PROGRAM.properties

    # check if loader already running
    if [ -e $PIDFILE ]; then 
        PID=`cat $PIDFILE`
        ps -p $PID > /dev/null 
        if [ $? != 1 ]; then
            echo "${PROGRAM} already running!"
            return 1
        fi
    fi

    $WMCXMLLIMITS_HOME/$PROGRAM                                                 \
        --config-file=$CONFIGFILE                                               \
        --user-db-url=$USER_DB_URL                                              \
        --host-db-urls=$HOST_DB_URLS                                            \
        --xml-db-urls=$XML_HOST_DB_URLS                                         \
        --xml-limits-table=//home/antispam/mascot/export/rank_xml_2.discrete2   \
        --yt-cluster=banach.yt.yandex.net                                       \
        </dev/null >/dev/null 2>&1 &

    RUNNED_PIDS="$RUNNED_PIDS $!"
    echo $! > $PIDFILE
    return 0
}

KillLoader() {
    PIDFILE=$WMCXMLLIMITS_HOME/$PROGRAM.pid

    if [ -e $PIDFILE ]; then 
        PID=`cat $PIDFILE`
        ps -p $PID > /dev/null 
        if [ $? = 1 ]; then
            echo "PID file exist, but process not found. PID file will be removed."
            rm $PIDFILE
            return 0
        else
            kill -KILL $PID > /dev/null
            if [ $? = 0 ]; then
                rm $PIDFILE
                return 0
            fi
        fi
    else 
        echo "PID file not found."
        return 1
    fi
}

LoaderState() {
    PIDFILE=$WMCXMLLIMITS_HOME/$PROGRAM.pid
    if [ -e $PIDFILE ]; then 
        PID=`cat $PIDFILE`
        ps -p $PID > /dev/null 
        if [ $? = 1 ]; then
            echo "PID file exist, but process not found. PID file will be removed."
            rm $PIDFILE
            return 1
        else
            return 0
        fi
    else 
        echo "No found!"
        return 1
    fi 
}

# execute command
case ${COMMAND} in
run)
    RunLoader
    ;;
state)
    LoaderState
    ;;
kill)
    KillLoader
    ;;
*)
    echo "Unknown command ${COMMAND}!"
    echo "Available commands are: run, state, kill"
    exit
    ;;
esac
