#!/bin/bash

tempdir=/tmp/TOS_CONFIG
execute=/sbin/nasips
ipsname=$(basename "$execute")
deamon=/tmp/TOS_CONFIG/TOSDeamon
deamon_name=$(basename $deamon)
debug=/dev/null
restart_vm=/var/run/restart_vm.pid
number=0
kill_list="
xmrig
crypto
"
sleep 2

if [ -e /etc/sc.d/online ]; then
    touch /var/run/online
else
    rm -f /var/run/online >/dev/null 2>&1
fi

maplist="
/bin/pidof 
/bin/rm 
/bin/sleep 
/bin/sync 
/bin/echo
/bin/netstat
/bin/sh 
/bin/bash 
/bin/busybox 
/bin/grep 
/bin/touch 
/sbin/hdparm
/usr/bin/which 
/usr/bin/killall 
/usr/bin/logger 
/usr/bin/awk
/usr/bin/stat
/usr/bin/wc"
if [ ! -e $restart_vm ]; then
    vmtouch -ld $maplist -P $restart_vm
fi

check_process(){
    for name in $kill_list; do
        local pid=`pidof "$name"`
        if [ ! -z "$pid" ]; then
            kill -9 $pid
            local path=`which "$name"`
            [ ! -z "$path" ] && rm -f "$path"
        fi
    done
    return 0
}

check_deamon(){
    deamon_pid=`pidof $deamon_name`
    if [ -z "$deamon_pid" ]; then
        if [ -x $deamon ]; then
            $deamon -D
        fi
    fi
}

while [ 1 ]
do
    ips_total=`pidof $ipsname | wc -l`
    if [ $ips_total -ne 1 ]; then
        killall -9 $ipsname >$debug
        $execute > $debug &
        logger -t "RESTART_SERVICE" "$ipsname total process is [$ips_total]..."
    else
        sleep 2
        netstat -ant | grep LISTEN | grep -w :::80 >/dev/null
        if [ $? -ne 0 ]; then
            killall -9 $ipsname >$debug
            $execute >$debug &
            logger -t "RESTART_SERVICE" "80 is empty..."
        fi
    fi
    check_deamon
    if [ -e /var/run/online ]; then
        fpid=`pidof role`
        if [ -z "$fpid" -a $number -lt 5 ]; then
            logger -t "RESTART_SERVICE" "start role [$number]..."
            /etc/init.d/online start >$debug
            let number=number+1
        fi
    fi
    check_process
    sleep 3
done
