#!/bin/sh
noontec_echo_info(){
	echo -e '\033[0;30;1m'WARN:"$1"'\033[0m'
	return 0
}
noontec_echo_success(){
	echo -e '\033[0;32;1m'SUCC:"$1"'\033[0m'
	return 0
}
noontec_echo_failure(){
	echo -e '\033[0;31;1m'FAIL:"$1"'\033[0m'
	return 1
}
noontec_echo_warning(){
	echo -e '\033[0;33;1m'WARN:"$1"'\033[0m'
	return 1
}
noontec_strstr(){
	[ "${1#*$2*}" = "$1" ] && return 1
	return 0
}
# Output PIDs of matching processes, found using pidof
noontec_pidspidof(){
	pidof -o $$ -o $PPID -o %PPID "$1" || pidof -o $$ -o $PPID -o %PPID "${1##*/}"
}
# check $pid to pids from /var/run* for {program}.  $pid should be declared
# Returns LSB exit code for the 'status' action.
noontec_pidsvarrun(){
    local base=${1##*/}
    local pid_file=${2:-/var/run/$base.pid}
    local pid=""
    if [ -f "$pid_file" ] ; then
        local line p
        read line < "$pid_file"
        for p in $line ; do
            [ -z "${p//[0-9]/}" -a -d "/proc/$p" ] && pid="$pid $p"
        done
		if [ -n "$pid" ]; then
			return 0
		fi
        return 1 # "Program is dead and /var/run pid file exists"
    fi
    return 3 # "Program is not running"
}
noontec_checkpid(){
    local i
    for i in $* ; do
        [ -d "/proc/$i" ] && return 0
    done
    return 1
}
#find the pid of a program.
noontec_serverpidofproc(){
    local RC pid pid_file=""
    # Test syntax.
    if [ "$#" = 0 ]; then
        echo "Usage: noontec_serverpidofproc [-p pidfile] {program}"
        return 1
    fi
    if [ "$1" = "-p" ]; then
        pid_file=$2
        shift 2
    fi
    local fail_code=3 # "Program is not running"
    # First try "/var/run/*.pid" files
    noontec_pidsvarrun "$1" "$pid_file"
    RC=$?
    if [ -n "$pid" ]; then
        echo $pid
        return 0
    fi
    [ -n "$pid_file" ] && return $RC
    noontec_pidspidof "$1" || return $RC
}
noontec_serverstatus() {
    local base pid pid_file=""
    # Test syntax.
    if [ "$#" = 0 ] ; then
        echo "Usage: status [-p pidfile] {program}"
        return 1
    fi
    if [ "$1" = "-p" ]; then
        pid_file=$2
        shift 2
    fi
    base=${1##*/}
    # First try "pidof"
    noontec_pidsvarrun "$1" "$pid_file"
    RC=$?
    if [ -z "$pid_file" -a -z "$pid" ]; then
        pid="$(noontec_pidspidof "$1")"
    fi
    if [ -n "$pid" ]; then
            echo "${base} (pid $pid) is running..."
            return 0
    fi
    case "$RC" in
        0)
            echo "${base} (pid $pid) is running..."
            return 0
            ;;
        1)
            echo "${base} dead but pid file exists"
            return 1
            ;;
    esac
    # See if /var/lock/subsys/${base} exists
    if [ -f /var/lock/subsys/${base} ]; then
        echo "${base} dead but subsys locked"
        return 2
    fi
    echo "${base} is stopped"
    return 3
}
noontec_killproc(){
    local RC killlevel= base pid pid_file= delay
    RC=0; delay=3
    # Test syntax.
    if [ "$#" -eq 0 ]; then
        echo "Usage: killproc [-p pidfile] [ -d delay] {program} [-signal]"
        return 1
    fi
    if [ "$1" = "-p" ]; then
        pid_file=$2
        shift 2
    fi
    if [ "$1" = "-d" ]; then
        delay=$2
        shift 2
    fi
    # check for second arg to be kill level
    [ -n "${2:-}" ] && killlevel=$2
    # Save basename.
    base=${1##*/}
    # Find pid.
    noontec_pidsvarrun "$1" "$pid_file"
    if [ -z "$pid_file" -a -z "$pid" ]; then
        pid="$(noontec_pidspidof "$1")"
    fi
    # Kill it.
    if [ -n "$pid" ] ; then
        [ "$BOOTUP" = "verbose" -a -z "${LSB:-}" ] && echo -n "$base "
        if [ -z "$killlevel" ] ; then
            if noontec_checkpid $pid 2>&1; then
                # TERM first, then KILL if not dead
                kill -TERM $pid >/dev/null 2>&1
                usleep 100000
                if noontec_checkpid $pid && sleep 1 && noontec_checkpid $pid && sleep $delay && noontec_checkpid $pid ; then
                    kill -KILL $pid >/dev/null 2>&1
                    usleep 100000
                fi
            fi
            noontec_checkpid $pid
            RC=$?
            [ "$RC" -eq 0 ] && noontec_echo_failure "$base shutdown" || noontec_echo_success "$base shutdown"
            RC=$((! $RC))
        # use specified level only
        else
            if noontec_checkpid $pid; then
                kill $killlevel $pid >/dev/null 2>&1
                RC=$?
                [ "$RC" -eq 0 ] && noontec_echo_success "$base $killlevel" || noontec_echo_failure "$base $killlevel"
            elif [ -n "${LSB:-}" ]; then
                RC=7 # Program is not running
            fi
        fi
    else
        if [ -n "${LSB:-}" -a -n "$killlevel" ]; then
            RC=7 # Program is not running
        else
            noontec_echo_failure "$base shutdown"
            RC=0
        fi
    fi
    # Remove pid file if any.
    if [ -z "$killlevel" ]; then
            rm -f "${pid_file:-/var/run/$base.pid}"
    fi
    return $RC
}
noontec_execcommandstrret(){
	command="$1"
	key="$2"
	#0/wrong,1/right
	#ethtool -s eth0 speed 100 2>&1|grep "Invalid";echo $?
	$command 2>&1|grep -q "$key"
	if [ $?	-eq 0 ]
	then
		#echo 1 //find the key
		return 1
	else
		#echo 0 //no find the key
		return 0
	fi
}
noontec_delstringline(){
        filename="$1"
        repace_str="$2"
        if [ -f "${filename}" ]; then
                busybox sed -i "/${repace_str}/d" ${filename} > /dev/null 2>&1
                if [ "$?" -ne 0 ];then
                        echo -1
                        return 1
                fi
        fi
        echo 0
        return 0
}
noontec_find_str(){
        filename="$1"
        find_str="$2"
        find_str="$(echo ${find_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"}     \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        #echo find_str:$find_str
        if [ $# -gt 2 ]; then
                delimiter="$3"
                filed="$4"
                result="$(busybox sed  -n "/^[ \t]*${find_str}.*$/"p  ${filename}|awk -F"${delimiter}" '{print $'$filed'}')"
                if [ "$?" -eq 0 ]
                then
                        echo "$result"
                else
                        echo 1
                        return 1
                fi
        else
                result="$(busybox sed -n "/^${find_str}/"p  ${filename})"
                if [ "$?" -eq 0 ]
                then
                        echo "$result"
                else
                        echo 1
                        return 1
                fi
        fi
        return 0
}
noontec_replace_str(){
        filename="$1"
        repace_str="$2"
        new_str="$3"
        repace_str="$(echo ${repace_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        new_str="$(echo ${new_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"}       \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        #busybox sed -i 's/'${repace_str}'/'${new_str}'/g' ${filename}
        busybox sed -i "s/${repace_str}/${new_str}/g" ${filename} > /dev/null 2>&1
        if [ "$?" -eq 0 ]; then
                echo 0
        else
                echo 1
                return 1
        fi
        return 0
}
noontec_replace_str1(){
        filename="$1"
        repace_str="$2"
        new_str="$3"
        repace_str="$(echo ${repace_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        new_str="$(echo ${new_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"}       \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        busybox sed -i "s/^${repace_str}/${new_str}/g" ${filename} > /dev/null 2>&1
        if [ "$?" -eq 0 ]; then
                echo 0
        else
                echo 1
                return 1
        fi
        return 0
}
noontec_replace_str2(){
        filename="$1"
        repace_str="$2"
        new_str="$3"
        repace_str="$(echo ${repace_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        new_str="$(echo ${new_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"}       \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        busybox sed -i "s/^[^#]*${repace_str}.*/${new_str}/" ${filename} > /dev/null 2>&1
        if [ "$?" -eq 0 ]; then
                echo 0
        else
                echo 1
                return 1
        fi
        return 0
}
noontec_replace_str3(){
        filename="$1"
        repace_str="$2"
        new_str="$3"
        repace_str="$(echo ${repace_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        new_str="$(echo ${new_str}|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"}       \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
        busybox sed -i "s/\s*#.*${repace_str}.*/${new_str}/" ${filename} > /dev/null 2>&1
        if [ "$?" -eq 0 ]; then
                echo 0
        else
                echo 1
                return 1
        fi
        return 0
}
#$1 date
#$2 func
#$3 param1
#$4 param2...
noontec_usbcopyaddtaskitem(){
	#echo params:$#
	if [ $# -lt 3  ];then
		echo 1
		return 1
	fi
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	#30 10 * * 1,2,3,4,5
	date="$1"
	parm1="$2"
	parm2="$3"
	parm3="$4"
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo parm1:$2,parm2:$3,parm3:$4
	#delete old item
	#echo usercontabfile:$usercontabfile
	#egrep -q -e  "$2 $3"	"$usercontabfile"
	info=$(egrep -e  "usbcopy"	"$usercontabfile")
	if [ $? -eq 0 ];then
		sed -i '/usbcopy/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	parm1="$(echo $2|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
	{if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	parm2="$(echo $3|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	parm3="$(echo $4|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	#echo usercontabfile:$usercontabfile
	#egrep -q -e  "$parm1 $parm2 $parm3"	"$usercontabfile"
	egrep -q -e  "$parm1 $parm2"	"$usercontabfile"
	if [ $? -eq 0 ];then
		#sed -i '/'$parm1' '$parm2' '$parm3'/d' "$usercontabfile"
		sed -i '/'$parm1' '$parm2'/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	echo "$*" >> "$usercontabfile"
	/etc/init.d/cron restart
	if [ $? -ne 0 ];then
		echo 1
		return 1
	fi
	echo 0
	return 0
}
noontec_usbcopydeltaskitembak(){
	#echo params:$#
	if [ $# -lt 3  ];then
		echo 1
		return 1
	fi
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	parm1="$(echo $2|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
	{if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	parm2="$(echo $3|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	parm3="$(echo $4|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo usercontabfile:$usercontabfile
	egrep -q -e  "$2 $3"	"$usercontabfile"
	if [ $? -eq 0 ];then
		sed -i '/'$parm1' '$parm2'/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	/etc/init.d/cron restart
	if [ $? -ne 0 ];then
		echo 1
		return 1
	fi
	echo 0
	return 0
}
noontec_usbcopydeltaskitem(){
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo usercontabfile:$usercontabfile
	info=$(egrep -e  "usbcopy" "$usercontabfile")
	if [ $? -eq 0 ];then
		sed -i '/usbcopy/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	/etc/init.d/cron restart
	if [ $? -ne 0 ]; then
		echo 1
		return 1
	fi
	echo 0
	return 0
}
noontec_usbcopygettaskitem(){
	#echo params:$#
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo usercontabfile:$usercontabfile
	info=$(egrep -e  "usbcopy"	"$usercontabfile")
	if [ $? -eq 0 ];then
		info=${info//\*/any}
		#echo info:$info
		echo $info |awk '{print $1 " " $2 " " $5 " " $6 " " $7}'
	fi
	return 0
}
##################################
#$1 date
#$2 func
#$3 param1
#example :noontec_internettimesynaddtaskitem "*/5 * * * *" "ntpdate" "asia.pool.ntp.org"
#time server:
#asia.pool.ntp.org
#time.windows.com
noontec_internettimesynaddtaskitem(){
	#echo params:$#
	if [ $# -lt 3  ];then
		echo 1
		return 1
	fi
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	#30 10 * * 1,2,3,4,5
	date="$1"
	parm1="$2"
	parm2="$3"
	parm3="$4"
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo parm1:$2,parm2:$3,parm3:$4
	#delete old item
	#echo usercontabfile:$usercontabfile
	#egrep -q -e  "$2 $3"	"$usercontabfile"
	info=$(egrep -e  "ntpdate" "$usercontabfile")
	if [ $? -eq 0 ];then
		sed -i '/ntpdate/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	parm1="$(echo $2|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
	{if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	parm2="$(echo $3|awk 'BEGIN{MYESCAP="/";NEWESCAP="\\/"} \
        {if(match($0,MYESCAP) > 0){gsub(MYESCAP,NEWESCAP,$0)}}END{print $0}')"
	#echo usercontabfile:$usercontabfile
	#egrep -q -e  "$parm1 $parm2 $parm3"	"$usercontabfile"
	egrep -q -e  "$parm1 $parm2"	"$usercontabfile"
	if [ $? -eq 0 ];then
		#sed -i '/'$parm1' '$parm2' '$parm3'/d' "$usercontabfile"
		sed -i '/'$parm1' '$parm2'/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	echo "$*" >> "$usercontabfile"
	/etc/init.d/cron restart
	if [ $? -ne 0 ];then
		echo 1
		return 1
	fi
	echo 0
	return 0
}
noontec_internettimesyndeltaskitem(){
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo usercontabfile:$usercontabfile
	info=$(egrep -e  "ntpdate" "$usercontabfile")
	if [ $? -eq 0 ];then
		sed -i '/ntpdate/d' "$usercontabfile"
		if [ $? -ne 0 ];then
			echo 1
			return 1
		fi
	fi
	/etc/init.d/cron restart
	if [ $? -ne 0 ];then
		echo 1
		return 1
	fi
	echo 0
	return 0
}
noontec_internettimesyngettaskitem(){
	local username=`whoami`
	if [ -z "$username" ];then
		echo 1
		return 1
	fi
	usercontabfile="/var/spool/cron/crontabs/$username"
	#echo usercontabfile:$usercontabfile
	info=$(egrep -e  "ntpdate" "$usercontabfile")
	if [ $? -eq 0 ];then
		info=${info//\*/any}
		#echo info:$info
		echo $info |awk '{print $1 " " $7}'
	fi
	return 0
}
noontec_getdevip(){
	devfilepath="/proc/net/dev"
	awk -F":" '$0 ~/:/ && $0 !~/lo/ && $0 !~/sit0/ && $0 !~/ipddp.*/ && $0 !~ /\w*\d*\.\d*/ {gsub(/:/,"",$1);print $1}' "$devfilepath" |while read devnm
	do
		ifconfig "$devnm" up > /dev/null 2>&1
		ip=""
		#ifconfig $devnm |grep -q "UP BROADCAST.*RUNNING" > /dev/null 2>&1
		devstatus=$(cat /sys/class/net/$devnm/carrier 2>/dev/null)
		echo devstatus:$devstatus
		if [ ! -z "$devstatus" ] && [ "$devstatus" = "1" ]
		then
			#status="up"
			ip="$(ifconfig $devnm|awk '/inet addr/ {print $2}'|awk -F: '{print $2}')"
			echo -e "$devnm $ip"
		else
			#status="down"
			#echo -e "$devnm $ip"
			continue
		fi
	done
}
#find it,then return 0,else return 1
check_port(){
	checkport=$1
	checkprotocol=$2
	echo $1 |egrep -q -E "^[0-9]+$"
	if [ $? -ne 0 ];then
		echo 1
		return 1
	fi
	if [ -z "$checkprotocol" ];then
		checkprotocol=t
	elif [ "$checkprotocol" = "tcp" ];then
		checkprotocol=t
	elif [ "$checkprotocol" = "udp" ];then
		checkprotocol=u
	else
		checkprotocol=t
	fi
	STATUS=$(netstat -an"$checkprotocol" | grep LISTEN |awk '$0 ~/^'$checkprotocol'/ {print $4}'|sed 's/.*:\([0-9]*\)$/\1/'|uniq |grep "\b$checkport\b")
	if [ $? -eq 0 ];then
		echo 0
		return 0
	else
		echo 1
		return 1
	fi
}
#turen off the log cashe if the param is "off"
noontec_writecacheforext4(){
	local writecacheswitch="off"
	if [ ! -z "$1" ];then
		if [  "$1" = "on" ];then
			writecacheswitch="on"
		else
			writecacheswitch="off"
		fi
	fi
	#find every disk,and do the same operation
	mount |awk '$0 !~/md9/ && $0 ~/md[0-9]*/{print $1,$3}' |sort|while read devpath mountpath
	do
		if [ "$devpath" == "/dev/md9" ];then
			continue
		fi
		echo devpath:$devpath,mountpath:$mountpath
		sync > /dev/null 2>&1
		sync > /dev/null 2>&1
		sync > /dev/null 2>&1
		umount "$devpath" > /dev/null 2>&1
		if [ $? -ne 0 ];then
			echo 101
			mount -o defaults,user_xattr,data=ordered,acl,usrquota,grpquota "$devpath" "$mountpath"
			return 1
		fi
		e2fsck -n "$devpath" > /dev/null 2>&1
		if [ $? -ne 0 ];then
			echo 102
			mount -o defaults,user_xattr,data=ordered,acl,usrquota,grpquota "$devpath" "$mountpath"
			return 1
		fi
		# if [ "$writecacheswitch" = "on" ];then
		# 	tune2fs -j "$devpath" > /dev/null 2>&1
		# else
		# 	tune2fs -O ^has_journal "$devpath" > /dev/null 2>&1
		# fi
		tune2fs -o journal_data_ordered "$devpath" > /dev/null 2>&1
		if [ $? -ne 0 ];then
			echo 103
			mount -o defaults,user_xattr,data=ordered,acl,usrquota,grpquota "$devpath" "$mountpath"
			return 1
		fi
		#disk sync
		e2fsck "$devpath" > /dev/null 2>&1
		if [ $? -ne 0 ];then
			echo 104
			mount -o defaults,user_xattr,data=ordered,acl,usrquota,grpquota "$devpath" "$mountpath"
			return 1
		fi
		mount -o defaults,user_xattr,data=ordered,acl,usrquota,grpquota "$devpath" "$mountpath"
		if [ $? -ne 0 ];then
			echo 105
			return 1
		fi
		#reboot
	done
	echo 0
	return 0
}
