#!/bin/sh
:<<!
Ver 1.3.1222
使用方法：
    放在adm目录里，和ADMConfig.ini同级；
	给予脚本执行权限：chmod 777 admflt.sh；
	脚本名+参数名执行对应功能，例：./admflt.sh start
参数说明：
    运行：start
	停止：stop
	重启：restart
	状态：status
守护进程：
	守护（添加计划任务用）：deamon
	例：* * * * * /mnt/sda1/7620a/admflt.sh deamon
!
RETVAL=0
admDIR=$(cd "$( dirname "$0"  )" && pwd)
admPID=$(pgrep -o $admDIR/adm)
admPnum=$(pgrep $admDIR/adm | wc -l)
admHTTPS=$(cat $admDIR/ADMConfig.ini | grep 'support_ssl=1')

addPORT(){
    iptables -t nat -A PREROUTING -p tcp --dport $1 -j REDIRECT --to-ports 18309
}
delPORT(){
    iptables -t nat -D PREROUTING -p tcp --dport $1 -j REDIRECT --to-ports 18309
}
reCheck(){
    reCheck=$(cat $admDIR/adm.error)
    if [ -n "$reCheck" ]; then
        echo -e "\n\033[41;37m$reCheck\033[0m"
        sh $0 stop >/dev/null 2>&1
    fi
}
start() {
		echo "adm" >> /opt/pid.txt
        if [ "$admPnum" -ge "1" ]; then
            ps | grep $admDIR | egrep -v "grep|$0" && echo -e "\033[1;31madm already running!\nplease do not repeat the operation!\033[0m"
            exit 0
        else
            delPORT 80 >/dev/null 2>&1
            delPORT 443 >/dev/null 2>&1
            rm -f $admDIR/adm.error >/dev/null 2>&1
            chmod 777 $admDIR/adm
            addPORT 80
            if [[ -n "$admHTTPS" ]]; then
                addPORT 443
            fi
            ($admDIR/adm &) 1>/dev/null 2>$admDIR/adm.error
        fi
        RETVAL=$?
        [ $RETVAL -eq 0 ] && ps | grep $admDIR/adm | grep -v "grep" && echo -e "\033[1;32madm start success!\033[0m"
        return $RETVAL
}

stop() {
        admPN=$(ps | grep $admDIR/adm | grep -v grep | wc -l)
        while [ "$admPN" -gt "0" ] ; do
            kill -9 $(pgrep -o $admDIR/adm)
            let "admPN=admPN-1"
        done
        delPORT 80
		if [[ -n "$admHTTPS" ]]; then
		    delPORT 443
		fi
        [ $? -eq 0 ] && echo -e "\033[1;31madm stop success!\033[0m"
        return $RETVAL
}
status(){
        if [[ -n "$admPID" ]]; then
            ps | grep $admDIR | egrep -v "grep|$0" && echo -e "\033[1;32madm already running!\033[0m"
        else
            echo -e "\033[1;31madm not running!\033[0m"
        fi
}
deamon(){
        runNUM=2
        runPN=$(pgrep $admDIR/adm | wc -l)
        while [ "$runNUM" -gt "0" ]; do
                if [[ -z "$admPID" ]]; then
                    sh $0 stop >/dev/null 2>&1
                    sh $0 start >/dev/null 2>&1
                elif [ "$runPN" -ge "2" ]; then
                    kill -9 $(pgrep -o $admDIR/adm)
                fi
            let "runNUM=runNUM-1"
            sleep 20
        done
#echo -e "\033[1;32madm deamon success!\033[0m"
}
case "$1" in
  start)
        start
        reCheck
		;;
  stop)
        stop
        ;;
  restart)
       sh $0 stop
       sh $0 start
        ;;
  status)
        status
        ;;
  deamon)
        deamon
        ;;
   *)
        echo $"Usage: $0 {start|stop|restart|status|deamon}"
        exit 1
        ;;
esac
exit $RETVAL