#!/bin/bash

# 强制设置 PATH
export PATH='/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin'

# 执行系统初始化配置文件
source /etc/profile

install_base=$(cd `dirname $0`; pwd)
shell_path=$install_base/bin
runing_file=$install_base/data/running

if [ "$#" -lt "1" ]; then
    echo "Usage: ./service.sh start|stop|restart|show|status|addcron"
    exit 1
fi

ACTION=$1

function configure {
    cd $shell_path
    crontab -l > ./crontab.bak
    cp ./crontab.bak ./crontab.tmp
    ./crontab.sh add crontab.tmp
    crontab crontab.tmp

    if [ $? -ne 0 ];then
        echo "Set crontab failed"
    else
        echo "Set crontab succ"
    fi

    rm crontab.tmp
}

function stopService {
    killall wxpaymonitor
    sleep 2
}

function startService {
    pnum=`ps -ef|/bin/grep "\./wxpaymonitor"|grep -v "/bin/grep"|grep -v "/bin/bash" |wc -l`
    if [ $pnum -lt 1 ]; then
        cd $install_base
        ./wxpaymonitor -d
    fi

    echo "start successful"
    ps -ef|/bin/grep "\./wxpaymonitor"|grep -v "/bin/grep"|grep -v "/bin/bash"

    # first run
    if [ ! -f $runing_file ];then
        configure 
        touch $runing_file
    fi
}

if [ "$ACTION" = "cron" -o "$ACTION" = "addcron" ]; then
    configure
    exit 0
fi

if [ "$ACTION" = "show" -o "$ACTION" = "status" ]; then
    ps -ef|/bin/grep "\./wxpaymonitor"|grep -v "/bin/grep"|grep -v "/bin/bash"
    exit 0
fi

if [ "$ACTION" = "shutdown" -o "$ACTION" = "restart" -o "$ACTION" = "stop" ]; then
    stopService
fi

if [ "$ACTION" != "shutdown" -a "$ACTION" != "stop" ]; then
    startService
fi
