#!/bin/sh

DPILINK=/usr/ramdisk/bin/padpi.so

DELAY100MS()
{
        myusleep=`which usleep 2>/dev/null`
        if [ "${myusleep}" != "" ]; then
                t=$(($1 * 100000))
                usleep $t
        else
                sleep .$1
        fi
}

panaos_exist()
{
	local fn

	for fn in `ps ax | awk '{print $5}' | grep panaos`
	do
		if [ "${fn}" = "/usr/ramdisk/bin/panaos" ]; then
			echo "YES"
			return
		fi
	done

        echo "NO"
}

# This script is the Policy scheduler, it is a
# very important script.
# This script has implement a simple framework
# for you to add handler for new defined events.

# Log event to the log file
# args: "event msg"
log_event()
{
	echo "`date "+%y/%m/%d %H:%M:%S"` $1" 
}

# restart the whole system
# this is usually used by sig db upgrade
upgrade_sigdb()
{
	local count
	local exited
	local cursec

	# stop datamon
	exited=0
	for loop in 1 2; do
		# stop datamon 
		errmsg=`/usr/ramdisk/bin/ipectrl stop datamon`
		# wait datamon to exit
		count=20
		while [ ${count} -gt 0 ]; do
			DELAY100MS 5
			datamon=`ps ax | grep ipe_datamon | grep -v grep`
			if [ "${datamon}" = "" ]; then
				exited=1
				break
			fi
			count=$((${count} - 1))
		done
	
		[ ${exited} -eq 1 ] && break
	done

	mkdir -p ${SYSPKGROOT}/tmp
	if [ ${exited} -eq 0 ]; then
		echo "ݲɼ޷ر" > ${SYSPKGROOT}/tmp/dpiupresult
		rm -Rf ${SYSPKGROOT}/upgrade/*
		return
	fi

	newdpiso=${SYSPKGROOT}/upgrade/dpi.so
	errmsg=`${FLOWEYE} ipe set path=${newdpiso}`
	if [ "$?" != "0" ]; then
		echo "${errmsg}" > ${SYSPKGROOT}/tmp/dpiupresult
		errmsg=`${RAMDISK}/bin/ipectrl start datamon`
		rm -Rf ${SYSPKGROOT}/upgrade/*
		return
	fi

	cp -f ${SYSPKGROOT}/upgrade/dict.so ${RAMDISK}/bin/
	cp -f ${RAMDISK}/bin/dict.so ${PGPATH}/bin/
	cp -f ${newdpiso} ${RAMDISK}/bin/
	cp -f ${RAMDISK}/bin/dpi.so ${PGPATH}/bin/
	sync

	#reload it from /usr/ramdisk/bin/dpi.so again!
	errmsg=`${FLOWEYE} ipe set path=${RAMDISK}/bin/dpi.so`
	
	DELAY100MS 5

	# restart datamon service
	${RAMDISK}/bin/ipectrl start datamon

	rm -Rf ${SYSPKGROOT}/upgrade/*
	echo "SUCCESS" > ${SYSPKGROOT}/tmp/dpiupresult
	sync
}

import_config()
{
	# Stop and waiting panaos exit
	count=50
	while [ ${count} -gt 0 ]; do
		errmsg=`${PGPATH}/bin/ipectrl stop panaos`
		DELAY100MS 2
		if [ ! -e /usr/ramdisk/var/pahugetlb/mem.txt ]; then 
			errmsg=`panaos_exist`
			[ "${errmsg}" = "NO" ] && break
		fi

		count=$((${count} - 1))
	done

	# upgrade config
	cp -f ${DATAPATH}/config/panabit.conf ${PGETC}/
	sync

	# start panaos
	DELAY100MS 1
	${PGPATH}/bin/ipectrl start panaos

	rm -f ${DATAPATH}/config/panabit.conf

	sync
}

autosync_action()
{
	[ ! -e ${RAMDISK}/bin/cfg_autosync ] && return 1

	case "$1" in
	"start")
		${RAMDISK}/bin/cfg_autosync &
		echo "cfg_autosync is started!"
		return 0
		;;

	"stop")
		# kill cfg_autosync if it exists
		ps ax | grep cfg_autosync | awk '{print $1, $6}' | \
		while read pid path; do
			if [ "${path}" = "${RAMDISK}/bin/cfg_autosync" ]; then
				kill -9 ${pid}
				echo "cfg_autosync is stopped!"
			fi
		done

		return 0
		;;

	"*")
		echo "unknown action \"$1\""
		return 1
		;;
        esac
}

# update the whole system
upgrade_system()
{
	local count
	local exited

	autosync_action stop

	exited=0
	for loop in 1 2; do
		# stop datamon 
		errmsg=`${PGPATH}/bin/ipectrl stop datamon`
		# wait datamon to exit
		count=20
		while [ ${count} -gt 0 ]; do
			DELAY100MS 5
			datamon=`ps ax | awk '{print $5}' | grep ipe_datamon`
			if [ "${datamon}" = "" ]; then
				exited=1
				break
			fi
			count=$((${count} - 1))
		done
	
		[ ${exited} -eq 1 ] && break
	done

	errmsg=`${PGPATH}/bin/ipectrl stop mgd`
	errmsg=`${PGPATH}/bin/ipectrl stop xping`
	errmsg=`${PGPATH}/bin/ipectrl stop httpd`
	errmsg=`${PGPATH}/bin/ipectrl stop newweb`
###	errmsg=`${PGPATH}/bin/ipectrl stop iked`
	errmsg=`${PGPATH}/bin/appctrl stop all`

	# Waiting panaos exit
	count=50
	while [ ${count} -gt 0 ]; do
		errmsg=`${PGPATH}/bin/ipectrl stop panaos`
		DELAY100MS 2
		if [ ! -e /usr/ramdisk/var/pahugetlb/mem.txt ]; then 
			errmsg=`panaos_exist`
			[ "${errmsg}" = "NO" ] && break
		fi

		count=$((${count} - 1))
	done

	# restart the whole system, delay 100ms again.
	DELAY100MS 1
	# Step 5: restart the whole system
	if [ -f ${PGPATH}/bin/dpi.so.new ]; then
		cp -f ${PGPATH}/bin/dpi.so.new ${RAMDISK}/bin/dpi.so
		mv ${PGPATH}/bin/dpi.so.new ${PGPATH}/bin/dpi.so
		sync
	fi
	
	${PGPATH}/bin/ipectrl start
	DELAY100MS 1
	
	# notify the browser the success flag.
	mkdir -p ${SYSPKGROOT}/tmp
	touch ${SYSPKGROOT}/tmp/sys_up_success

	# exit this monitor as the new monitor has 
	# been running
	echo "Upgrade ok, monitor exit!"
	exit 0
}

# handle all events
handle_events()
{
	local evtfile=$1
	local event
	local arg1
	local arg2

	exec 0<${evtfile}
	while read event arg1 arg2
	do
		case ${event} in
		"upgrade_sigdb")
			upgrade_sigdb
			;;

		"upgrade_system")
			upgrade_system
			;;

		"import_config")
			import_config
			;;

		"start_autosync")
			autosync_action start
			;;

		"stop_autosync")
			autosync_action stop
			;;

		"start_datamon")
			${PGPATH}/bin/ipectrl start datamon
			;;

		*)
			log_event "WARNNING Unknown event \"${event}\"!"
			;;
		esac
	done
}


# Assign all interrupts to CPU0
irq_bind()
{
        osver=`uname -r | cut -d'.' -f1`
        [ ${osver} -lt 8 ] && return

        for irqno in `vmstat -i | grep "^irq" | cut -d':' -f1 | sed -e "s/irq//g"`
        do
                cpuset -l0 -x ${irqno}
        done
}

# Start network
start_nz0()
{
        # Setup admin interface
        . ${PGETC}/ifadmin.conf
	ifconfig ${ADMIN_PORT} ${ADMIN_IP} netmask ${ADMIN_MASK}

        # Setup gateway.
        gateway=`netstat -rn | grep "^default" | awk '{print $2}' 2>/dev/null`
        if [ "${gateway}" != "${GATEWAY}" ]; then
                ermsg=`route delete default 2>&1`
                route add default ${GATEWAY} >/dev/null
                echo "Set default gateway to ${GATEWAY}"
        fi
}

authcode_clean()
{
	local curtime=`date +%s`
        local codedir=/usr/ramdisk/authcode
        if [ -d "${codedir}" ]; then
                filelist=`ls ${codedir}`
                for codefile in ${filelist}
                do
                        st_mtime=`stat -c %Y ${codedir}/${codefile}`
                        st_mtime=$((${st_mtime} + 60))
                        [ ${curtime} -gt ${st_mtime} ] && rm -f ${codedir}/${codefile}
               done
        fi
}

# Check logins
weblogin_clean()
{
	local filelist
	local loginfile
	local curtime

	authcode_clean

	filelist=`ls /usr/ramdisk/weblogin/paonline_* 2>/dev/null`
	[ "$?" != "0" ] && return

	curtime=`date +%s`
	for loginfile in ${filelist}
	do
  		st_mtime=`stat -c %Y ${loginfile}`
		st_mtime=$((${st_mtime} + ${webexit}))
		[ ${curtime} -gt ${st_mtime} ] && rm -f ${loginfile}
	done
}

. /etc/PG.conf
if [ -f ${PGETC}/httpd.conf ]; then
	HTTPS_PORT=`grep port= ${PGETC}/httpd.conf | cut -d"=" -f2`
	HTTPD_MAX=`grep maxchld= ${PGETC}/httpd.conf | cut -d"=" -f2`
fi

[ "${HTTPS_PORT}" = "" ] && HTTPS_PORT=443
[ "${HTTPD_MAX}" = "" ] && HTTPD_MAX=200

webexit=1800
[ -f ${PGETC}/webexit.conf ] && . ${PGETC}/webexit.conf 

pending_event_file=${PGETC}/log/pending_events
current_event_file=${PGETC}/log/current_events
irqbind_count=0
canbindirq=0
osver=`uname -r | cut -d'.' -f1`
[ ${osver} -ge 8 ] && canbindirq=1
lastntptime=`date +%s`
RAMDISK=/usr/ramdisk
SYSPKGROOT="${RAMDISK}"
HTTPD="${RAMDISK}/bin/ipe_httpd"
NTMLOGD="${RAMDISK}/bin/ntmlogd"
CERFILE="${RAMDISK}/admin/admin.pem"
ADMIN="${RAMDISK}/admin"
DDNS="${RAMDISK}/app/ddns/ipe_ddns"
PPPOE_PLAN="${RAMDISK}/bin/ipe_pppoeplan"
AIDE_REMARKMAN="${RAMDISK}/admin/cgi-bin/common/aide_remarkman"
aide_time=`date +%s`
FLOWEYE=/usr/ramdisk/bin/floweye
# Rename to wahttpd for killall
cp -f ${RAMDISK}/bin/ipe_httpd ${RAMDISK}/bin/wahttpd

# Start cfg_autosync
# autosync_action start

timecnt=0
while true; do
	sleep 1

	# Process pending events
	if [ -f ${pending_event_file} ]; then
		mv ${pending_event_file} ${current_event_file}
		handle_events ${current_event_file}
		rm -f ${current_event_file}
	fi

	weblogin_clean

	# check healthy of httpd
	httpd_status=0
	webauth_status=0
	for port in `ss -ltno | awk '{ print $4}' | awk -F":" '{print $NF}'`
	do
		if [ "${port}" = "${HTTPS_PORT}" ]; then
			httpd_status=1
		elif [ "${port}" = "8010" ]; then
			webauth_status=1
		fi
	done

        if [ ${httpd_status} -eq 0 ]; then
                ${HTTPD} -C "${PGETC}/httpd.conf"
        fi

	if [ -e ${NTMLOGD} ]; then
		status=`ps auxwww | grep ntmlogd | grep -v grep`
		if [ "X$status" = "X" ]; then
			/usr/ramdisk/bin/ipectrl start ntmlogd
		fi
	fi

	# ntpdate
	cursecs=`date +%s`
	elapse=$((${cursecs} - ${lastntptime}))
	if [ ${elapse} -ge 3600 ]; then
		lastntptime="${cursecs}"
		if [ -f ${PGETC}/ntp.conf ]; then
			. ${PGETC}/ntp.conf
			if [ "${ntpserver_ip}" != "0.0.0.0" ]; then
				ntpdate -t 20 ${ntpserver_ip}
				hwclock -w
			fi
		fi
	fi

	# clean invalid remark on 1 day
	if [ $((`date +%s` - ${aide_time})) -gt 86400 ]; then
		aide_time=`date +%s`
		${AIDE_REMARKMAN} -r
	fi
done
