#!/bin/sh

# 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()
{
	# Copy packages
	cp -f ${SYSPKGROOT}/upgrade/floweye ${PGPATH}/bin/
	cp -f ${SYSPKGROOT}/upgrade/ipe_datamon ${PGPATH}/bin/
	cp -f ${SYSPKGROOT}/upgrade/panaos ${PGPATH}/bin/
	errmsg=`cp -f ${PGETC}/version ${PGETC}/version.old 2>&1`
	errmsg=`cp -f ${SYSPKGROOT}/upgrade/version ${PGETC}/`
	sync

	# Sync it into ramdisk
	if [ -f ${RAMDISK}/PG.conf ]; then
		cp -f ${SYSPKGROOT}/upgrade/floweye ${RAMDISK}/bin/
		cp -f ${SYSPKGROOT}/upgrade/ipe_datamon ${RAMDISK}/bin/
		cp -f ${SYSPKGROOT}/upgrade/panaos ${RAMDISK}/bin/
	fi

	# stop releated services
	${PGPATH}/bin/ipectrl stop datamon
	${PGPATH}/bin/ipectrl stop xping
	${PGPATH}/bin/ipectrl stop panaos
	# sleep for 200ms
	sleep .2
	# start releated services
	${PGPATH}/bin/ipectrl start panaos
	${PGPATH}/bin/ipectrl start datamon
	${PGPATH}/bin/ipectrl start xping

	rm -Rf ${SYSPKGROOT}/upgrade/*
	mkdir -p ${SYSPKGROOT}/tmp
	touch ${SYSPKGROOT}/tmp/sigdb_up_success
	sync
}

import_config()
{
	# stop panaos
	${PGPATH}/bin/ipectrl stop panaos
	${PGPATH}/bin/ipectrl stop panaos
	sleep 1

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

	# start panaos
	${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

	autosync_action stop

	# Step 1: stop all services except monitor
	errmsg=`${PGPATH}/bin/ipectrl stop datamon`
	# wait datamon to exit
	count=20
	while [ ${count} -gt 0 ]; do
		datamon=`ps ax | awk '{print $5}' | grep ipe_datamon`
		[ "${datamon}" = "" ] && break

		${PGPATH}/bin/ipectrl stop datamon
		sleep .1
		count=$((${count} - 1))
	done

	errmsg=`${PGPATH}/bin/ipectrl stop mgd`
	errmsg=`${PGPATH}/bin/ipectrl stop xping`
	errmsg=`${PGPATH}/bin/ipectrl stop httpd`

	sleep .1
	errmsg=`${PGPATH}/bin/ipectrl stop panaos`

	# Waiting panaos exit
	count=20
	while [ ${count} -gt 0 ]; do
		panaos=`ps ax | awk '{print $5}' | grep panaos`
		[ "${panaos}" = "" ] && break

		${PGPATH}/bin/ipectrl stop panaos
		sleep .1
		count=$((${count} - 1))
	done

	# restart the whole system
	sleep .1
	# Step 5: restart the whole system
	${PGPATH}/bin/ipectrl start

	sleep 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
}

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

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

	curtime=`date +%s`
	for loginfile in ${filelist}
	do
  		st_mtime=`${STAT} -f %m ${loginfile}`
		st_mtime=$((${st_mtime} + 1800))
		[ ${curtime} -gt ${st_mtime} ] && rm -f ${loginfile}
	done
}

# Check log
logfile_check()
{
	local logfile
	local minsec 
	local filesec

	minsec=`date +%s`
	minsec=$((${minsec} - 14 * 86400))
	cd ${DATAPATH}
	for logfile in `ls web_*.log`
	do
		filesec=`${STAT} -f %c ${logfile}`
		[ ${filesec} -le ${minsec} ] && rm -f ${logfile}
	done

	for logfile in `ls alert_*.log`
	do
		filesec=`${STAT} -f %c ${logfile}`
		[ ${filesec} -le ${minsec} ] && rm -f ${logfile}
	done
}

. /etc/PG.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`
STAT=${PGPATH}/bin/stat

RAMDISK=/usr/ramdisk
SYSPKGROOT="${RAMDISK}"
HTTPD="${RAMDISK}/bin/ipe_httpd"
CERFILE="${RAMDISK}/admin/admin.pem"
ADMIN="${RAMDISK}/admin"
HTTPDPIDFILE=/var/tmp/httpd.pid
WAPIDFILE=/var/tmp/webauth.pid
APPWEBDIR=/usr/appweb
APPWEBS="/usr/appweb/appweb/bin/appwebs"
LIGHTTPD=/usr/local/sbin/lighttpd

# 2013.02-01 --> add var for idping
lastidpingtime=${lastntptime}

# 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

	if [ ${canbindirq} -ne 0 -a ${irqbind_count} -le 5 ]; then
		irq_bind
		irqbind_count=$((${irqbind_count} + 1))
	fi

	if [ "${ADMIN_PORT}" = "nz0" ]; then
		ipaddr=`ifconfig nz0 inet | grep inet | awk '{print $2}'`
		[ "${ipaddr}" = "" -o "${ipaddr}" = "0.0.0.0" ] && start_nz0
	fi

	timecnt=$((${timecnt} + 1))
	[ ${timecnt} -le 5 ] && continue
	timecnt=0

	weblogin_check

	logfile_check

	# check healthy of httpd
	httpd_running=0
	webauth_running=0
	webauthpid=""
	httpdpid=""
	if [ -f ${HTTPDPIDFILE} ]; then
		httpdpid=`cat ${HTTPDPIDFILE}`
		[ -f ${WAPIDFILE} ] && webauthpid=`cat ${WAPIDFILE}`
		for pid in `ps -ax | grep "httpd" | awk '{print $1}'`; do
			[ "${httpdpid}" != "" -a "${pid}" = "${httpdpid}" ] && httpd_running=1
			[ "${webauthpid}" != "" -a "${pid}" = "${webauthpid}" ] && webauth_running=1
		done
	else
		for cmd in `ps -ax | awk '{print $5}'`; do
			if [ "${cmd}" = "${HTTPD}" ]; then
				httpd_running=1
				break
			fi
		done
	fi

	if [ ${httpd_running} -eq 0 ]; then
		[ "${HTTPS_PORT}" = "" ] && HTTPS_PORT=443
		${HTTPD} -u root -T gb2312 -p ${HTTPS_PORT} -S -E ${CERFILE} -i ${HTTPDPIDFILE} -d ${ADMIN} -M 1
	fi

	if [ ${webauth_running} -eq 0 ]; then
		${HTTPD} -noauth -u root -T gb2312 -p 8010 -i ${WAPIDFILE} -d ${RAMDISK}/login -M 1
	fi

	if [ -x ${LIGHTTPD} ]; then
		lighty_user=0 
		for arg in `ps axw | grep lighttpd | grep -v grep | awk '{print $5"|"$7}'`
		do
			path=${arg%%|*}
			conf=${arg#*|/*/*/*/}
			if [ "${path}" = "${LIGHTTPD}" -o "${path}" = "lighttpd" ]; then
				[ "${conf}" = "lighty_user.conf" ] && lighty_user=1
			fi
		done

		if [ ${lighty_user} -eq 0 ]; then
			mkdir -p /usr/ramdisk/tmp
			${LIGHTTPD} -f ${RAMDISK}/etc/lighty_user.conf
		fi 
	elif [ -x ${APPWEBS} ]; then
		appweb=0
		for path in `ps ax | grep appwebs | awk '{print $5}'`
		do
			if [ "${path}" = "${APPWEBS}" ]; then
				appweb=1
				break
			fi
		done

		if [ ${appweb} -eq 0 ]; then
			mkdir -p /usr/ramdisk/tmp
			${APPWEBS} --config ${APPWEBDIR}/appweb/appweb.conf &
		fi
	fi

	# show led information
        if [ "${MACHINE}" = "LH7536" ]; then
		if [ -f ${RAMDISK}/PG.conf ]; then
                	summary=`${RAMDISK}/bin/floweye app stat showsum app=group | grep total`
                	bpsup=`echo ${summary} | cut -d' ' -f13`
                	bpsdown=`echo ${summary} | cut -d' ' -f14`
                	${RAMDISK}/bin/lcdshow cuau1 ${bpsup} ${bpsdown}
		else
                	summary=`${PGPATH}/bin/floweye app stat showsum app=group | grep total`
                	bpsup=`echo ${summary} | cut -d' ' -f13`
                	bpsdown=`echo ${summary} | cut -d' ' -f14`
                	${PGPATH}/bin/lcdshow cuau1 ${bpsup} ${bpsdown}
		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
			[ "${ntpserver_ip}" != "0.0.0.0" ] && ntpdate -t 20 ${ntpserver_ip}
		fi
	fi
  
	# 2013.02-01 --> add idping
	cursecs=`date +%s`
	elapse=$((${cursecs} - ${lastidpingtime}))
	if [ ${elapse} -ge 5 ]; then
		lastidpingtime="${cursecs}"
		if [ -f ${PGETC}/idping.conf ]; then 
			 . ${PGETC}/idping.conf
			 if [ "${server_ip}" != "" -a "${server_ip}" != "0.0.0.0" -a \
            "${server_port}" != "" -a "${server_port}" != "0" -a \
            "${server_tag}" != "" ]; then
            if [ -f ${RAMDISK}/PG.conf ]; then
                [ -f ${RAMDISK}/bin/idping ] && ${RAMDISK}/bin/idping ${server_ip} ${server_port} ${server_tag}
            else
                [ -f ${PGPATH}/bin/idping ] && ${PGPATH}/bin/idping ${server_ip} ${server_port} ${server_tag}
            fi
        fi
		fi
	fi
  
	# 2013.06-22 --> add yunnan_monitor
	if [ -x ${RAMDISK}/bin/yunnan_monitor ]; then
		yunnan=0 
		for arg in `ps axw | grep yunnan_monitor | grep -v grep`
		do
			yunnan=1 
			break
		done

		if [ "${yunnan}" = "0" ]; then
			${RAMDISK}/bin/yunnan_monitor
		fi
	fi
done
