#!/bin/bash

WORKSPACE=$(cd $(dirname $0)/; pwd)
cd $WORKSPACE

#export LD_LIBRARY_PATH=./:$LD_LIBRARY_PATH

mkdir -p var

module=AdoreMixV8.0.2_console_linux
app=$module
conf=config.ini
pidfile=var/app.pid
logfile=var/app.log
chmod +x $app

function check_pid() {
    if [ -f $pidfile ];then
        pid=`cat $pidfile`
        if [ -n $pid ]; then
            running=`ps -p $pid|grep -v "PID TTY" |wc -l`
            return $running
        fi
    fi
    return 0
}

function start() {
    check_pid
    running=$?
    if [ $running -gt 0 ];then
        echo -n "$app now is running already, pid="
        cat $pidfile
        return 1
    fi



    TIMESTAMP=$(date +"%Y%m%d%H%M%S")
	BACKUP_FILE="${logfile}_${TIMESTAMP}"
cp  "$logfile" "$BACKUP_FILE"
    nohup ./$app  config.ini  &> $logfile &
    echo $! > $pidfile
    echo "$app started..., pid=$!"
    tail -f $logfile
}

function stop() {
    pid=`cat $pidfile`
    kill $pid
    echo "$app stoped..."
}

function restart() {
    stop
    sleep 1
    start
}

function status() {
    check_pid
    running=$?
    if [ $running -gt 0 ];then
        echo -n "$app now is running, pid="
        cat $pidfile
    else
        echo "$app is stoped"
    fi
}

function tailf() {
    tail -f $logfile
}


function help() {
    echo "$0 start|stop|restart|status|tail"
}

if [ "$1" == "" ]; then
    help
elif [ "$1" == "stop" ];then
    stop
elif [ "$1" == "start" ];then
    start
elif [ "$1" == "restart" ];then
    restart
elif [ "$1" == "status" ];then
    status
elif [ "$1" == "tail" ];then
    tailf
else
    help
fi
