#!/bin/sh

if [ "$1" = "restore" ]; then
	. /etc/PG.conf
	
	echo -n "Are you sure to restore the original configuration[y/n]?"
	read answer
	if [ "${answer}" = "y" -o "${answer}" = "Y" ]; then
		echo "Begin to restore admin interface configuration...... "
		if [ "${TOPSEC}" = "" ]; then
			adminip="192.168.0.200"
			gatewayip="192.168.0.1"
		else
			adminip="192.168.1.254"
			gatewayip="192.168.1.1"
		fi
		echo "ADMIN_IP=${adminip}
ADMIN_MASK=255.255.255.0
GATEWAY=${gatewayip}" > ${PGETC}/ifadmin.conf
		echo "New configuration is: "
		cat ${PGETC}/ifadmin.conf
		
		echo "******Begin to stop Panabit......"
		${PGPATH}/bin/ipectrl stop
		sleep 3
		echo "******Panabit is stopped!"

		echo "******Remove current configuration of Panaos......"
		rm -rf ${PGETC}/panabit.conf
		echo "******Current configurations of Panaos is removed!"

		echo "******Begin to restart Panabit......"
		${PGPATH}/bin/ipectrl start
		sleep 3
		echo "******Panabit is started!"

		echo "******Success!"
	fi

	exit 0
fi

curuser=`id -nu`
if [ "${curuser}" != "root" ]; then
	echo "ipectrl can only run as root user!"
	exit 1
fi

if [ ! -e /etc/PG.conf ]; then
	echo "/etc/PG.conf not exist!"
	exit 1
fi

exec 0</etc/PG.conf
while read tagvalue; do
	if [ "`echo ${tagvalue} | cut -d'=' -f1`" != "" ]; then
		eval "export ${tagvalue}"
	fi
done

if [ "${PGPATH}" = "" ]; then
	echo "/etc/PG.conf is corrupted!!!"
	cat /etc/PG.conf
	exit 0
fi

if [ ! -d ${PGPATH} ]; then
	echo "/etc/PG.conf is corrupted for ${PGPATH} not exist!"
	exit 0
fi

# Create RAM disk
RAMDISK=/usr/ramdisk
rammd=`df | grep "${RAMDISK}"`
if [ "${rammd}" = "" ]; then
	mkdir -p ${RAMDISK}
	mdmfs -M -s 32m md1 ${RAMDISK}
	if [ "$?" != "0" ]; then
		echo "FAIL TO CREATE RAMDISK!"
		exit 1
	fi
fi

# Sync the ramdisk with original data
if [ "$1" = "start" ]; then
	# 2013-08-19 remove sftp and scp
	msg=`killall -9 sftp-server 2>/dev/null`
	rm -f /usr/bin/scp
	rm -f /usr/libexec/sftp-server

	# Login page
	mkdir -p ${RAMDISK}/login/cgi-bin/
	cp -Rf ${PGPATH}/admin/cgi-bin/Login/* ${RAMDISK}/login/cgi-bin/
	cp -f ${PGPATH}/admin/img/login_logo.gif ${RAMDISK}/login/

	# 2013-06-26 add yunnan api interface "external" directory
	if [ -e ${PGPATH}/admin/cgi-bin/external ]; then
		mkdir -p ${RAMDISK}/login/external/
		cp -Rf ${PGPATH}/admin/cgi-bin/external/* ${RAMDISK}/login/external/
	fi

	needsync=1
	if [ -e ${RAMDISK}/etc/panabit.inf ]; then
		oridata=`cat ${PGPATH}/etc/panabit.inf`
		ramdata=`cat ${RAMDISK}/etc/panabit.inf`
		[ "${oridata}" = "${ramdata}" ] && needsync=0
	fi

	if [ ${needsync} -ne 0 ]; then
		cp -Rf ${PGPATH}/* ${RAMDISK}/
		cp -f /etc/PG.conf ${RAMDISK}/
	else
		if [ "$2" = "" -o "$2" = "panaos" ]; then
			cp -f ${PGPATH}/bin/panaos  ${RAMDISK}/bin/
			cp -f ${PGPATH}/bin/floweye ${RAMDISK}/bin/
			[ -f /sbin/floweye ] && cp -f ${PGPATH}/bin/floweye /sbin/
      
      # 2013-06-26 add sync ipectrl to /usr/bin/ipectrl
      [ -f /usr/bin/ipectrl ] && cp -f ${PGPATH}/bin/ipectrl /usr/bin/ipectrl

			cp -f ${PGPATH}/admin/.htpasswd ${RAMDISK}/admin/
		fi
	fi
fi

# New PGPATH
export PGPATH="${RAMDISK}"

# floweye need to revoke rrdtool, so put it to the /bin
# to let floweye will find it.
cp -f ${PGPATH}/bin/floweye /usr/bin/

sync

FLOWEYE=${PGPATH}/bin/floweye
PGCFGPATH=${PGPATH}/etc
PGBIN=${PGPATH}/bin
HTTPD=${PGPATH}/bin/ipe_httpd
ADMIN=${PGPATH}/admin
HTTPPIDFILE=/var/tmp/httpd.pid
APPWEBDIR=/usr/appweb
WAPIDFILE=/var/tmp/webauth.pid
LIGHTTPD=/usr/local/sbin/lighttpd

# Create the log directory
mkdir -p ${PGETC}/log
mkdir -p ${DATAPATH}/config
mkdir -p ${DATAPATH}/tmp

sync

# 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_network()
{
	# Setup admin interface
	. ${PGETC}/ifadmin.conf
	ipaddr=`ifconfig ${ADMIN_PORT} | grep inet | awk '{print $2}'`
	if [ "${ipaddr}" != "${ADMIN_IP}" -a \
	     "${ADMIN_IP}" != "" -a "${ADMIN_MASK}" != "" ]; then
		ifconfig ${ADMIN_PORT} ${ADMIN_IP} netmask ${ADMIN_MASK}
	fi

	# 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

	ifconfig ${ADMIN_PORT}
	echo "network is started!"
	return 0
}

# Start kernel
start_kernel()
{
	if [ "`uname -r | cut -d'.' -f1`" != "9" ]; then
		# Load new em driver
		if [ "`kldstat | grep if_em`" = "" ]; then
			errmsg=`kldload ${PGPATH}/kernel/if_em.ko 2>&1`
        	fi

		if [ "`kldstat | grep ixgbe`" = "" ]; then
			errmsg=`kldload ${PGPATH}/kernel/ixgbe.ko 2>&1`
        	fi
	fi

	# Load joskm
	if [ "`kldstat | grep joskm`" = "" ]; then
		kldload ${PGPATH}/kernel/joskm.ko
		# Put default set to CPU 0
		cpuset -l 0 -s 1
	fi

	# Load josnet
	. ${PGPATH}/etc/panabit.inf
	if [ -f ${PGPATH}/kernel/josnet.ko -a \
	     "`kldstat | grep josnet`" = "" ]; then
		kldload ${PGPATH}/kernel/josnet.ko
	fi

	sysctl net.inet.tcp.msl=2000

	return 0
}

httpd_action()
{
	case "$1" in
	"start")
		# add user guest if not exist
		guest=`cat ${ADMIN}/.htpasswd | grep "guest:"`
		if [ "${guest}" = "" ]; then
			. ${PGPATH}/etc/panabit.inf
			if [ ${JOS_RELEASE} -ne 2 ]; then
				echo "guest:guest" >> ${ADMIN}/.htpasswd
			fi
		fi

		rm -rf ${ADMIN}/tmp
		mkdir -p ${ADMIN}/tmp
		echo "Starting ipe_httpd ......"
		[ "${HTTPS_PORT}" = "" ] && HTTPS_PORT=443
		${HTTPD} -u root -T gb2312 -p ${HTTPS_PORT} -S -E ${ADMIN}/admin.pem -i ${HTTPPIDFILE} -d ${ADMIN} -M 1
		echo "ipe_httpd is started!"

		# Start WEB AUTH server
		${HTTPD} -noauth -u root -T gb2312 -p 8010 -i ${WAPIDFILE} -d ${RAMDISK}/login -M 1
		echo "Web auth http server started at 8010 port!"
		
		return 0
		;;

	"stop")
		killall ipe_httpd
		echo "httpd is stopped!"
		return 0
		;;

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

monitor_action()
{
	case "$1" in
	"start")
		${PGBIN}/ipe_monitor &
		echo "ipe_monitor is started!"
		return 0
		;;

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

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

		return 0
		;;

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

	esac
}

datamon_action()
{
	case "$1" in
	"start")
		${PGBIN}/ipe_datamon &
		echo "data monitor is started!"
		return 0
		;;

	"stop")
		# kill monitor if it exists
		killall ipe_datamon
		return 0
		;;

	"*")
		echo "unknow action \"$1\""
		;;

	esac
}

xping_action()
{
	case "$1" in
	"start")
		${PGBIN}/ipe_xping &
		;;

	"stop")
		killall ipe_xping
		;;

	"*")
		echo "unknown action \"$1\""
		;;

	esac
}

mgd_action()
{
	case "$1" in
	"start")
		${PGBIN}/ipe_mgd &
		;;

	"stop")
		killall ipe_mgd
		;;

	"*")
		echo "unknown action \"$1\""
		;;

	esac
}

panaos_action()
{
	case "$1" in
	"start")
		# 2013.02-01 --> add dns.dat, so mv dns.dat to panaetc dir
		if [ -f "${PGPATH}/etc/dns.dat" ]; then
			cp -f ${PGPATH}/etc/dns.dat ${PGETC}/
			rm -rf ${PGPATH}/etc/dns.dat
		fi
    
		# let system create core file in ${DATAPATH}
		cd ${DATAPATH}
		${PGBIN}/panaos 
		cd -
    
		# 2013.02-01 --> add new function to monitor, so must reboot ipe_monitor
		sleep 6 && ${PGBIN}/ipectrl restart monitor &
		;;

	"stop")
		panaospid=`sysctl -n kern.jos.ipe_mgrpid`
		if [ "${panaospid}" != "" -a ${panaospid} -ne 0 ]; then
			kill -USR1 ${panaospid}
		fi
		;;

	"*")
		echo "unknown action \"$1\""
		;;

	esac
}

appweb_action()
{
	case "$1" in
	"start")
		if [ -e ${APPWEBDIR} -a -e ${APPWEBDIR}/appweb/bin/appwebs ]; then
			mkdir -p /usr/ramdisk/tmp
			${APPWEBDIR}/appweb/bin/appwebs --config ${APPWEBDIR}/appweb/appweb.conf &
			echo "appweb start!"
		else
			echo "appweb start fail, it not exist!"
		fi
		;;

	"stop")
		killall appwebs
		echo "appweb stop!"
		;;

	"*")
		echo "unknow action \"$1\""
		;;
	esac
}

# 2013-08-01 add lighttpd web server action
lighttpd_action()
{
	case "$1" in
	"start")
		if [ -x ${LIGHTTPD} ]; then
			# Start new WEB server
			mkdir -p /usr/ramdisk/tmp
			${LIGHTTPD} -f ${PGPATH}/etc/lighty_user.conf
				echo "lighttp start!"
		else
			echo "lighttp start fail, it not exist!"
		fi
		;;

	"stop")
		killall -15 lighttpd
		echo "lighttp stop!"
		;;

	"*")
		echo "unknow action \"$1\""
		;;
	esac
}

if [ "$1" = "help" ]; then
	echo "start network : start network"
	echo "start httpd: start httpd daemon"
	echo "start monitor: start monitor service"
	echo "start kernel: load kernel module"
	echo "start datamon: start data monitor"
	echo "start xping: start xping engine"
	echo "start all: start all above service"

	echo ""
	echo "stop httpd: stop httpd daemon"
	echo "stop monitor: stop monitor service"
	echo "stop datamon: stop data monitor"
	echo "stop xping: stop xping engine"
	echo "stop all: stop all above service"

	echo "restore: restore the original configuration"
	exit 0
fi

# 2013.02-01 --> add new function for monitor, reboot ipe_monitor
if [ "$1" = "restart" ]; then
	target="$2"
	[ "${target}" = "" ] && target="all"
  
  case "${target}" in
	"monitor")
    monitor_action "stop"
    monitor_action "start"
		;;
	*)
		echo "undefined parameter '$2'"
		;;
	esac
fi

if [ "$1" = "start" ]; then
	target="$2"
	[ "${target}" = "" ] && target="all"

	case "${target}" in
	"httpd")
		httpd_action "start"
		;;

	"monitor")
		monitor_action "start"
		;;

	"datamon")
		datamon_action "start"
		;;

	"xping")
		xping_action "start"
		;;

	"mgd")
		mgd_action "start"
		;;

	"kernel")
		start_kernel
		;;

	"network")
		start_network
		;;

	"panaos")
		panaos_action "start"
		;;

	"appweb")
		appweb_action "start"
		;;

	# 2013-08-01 add lighttpd web server  
	"lighttpd")
		lighttpd_action "start"
		;;

	"all")
		start_kernel
		panaos_action  "start"
		start_network
		httpd_action   "start"
		monitor_action "start"
		datamon_action "start"
		xping_action   "start"
		mgd_action     "start"
		appweb_action  "start"

		# 2013-08-01 add lighttpd web server  
		lighttpd_action "start"

		if [ "${MAIN_RTPORT}" != "" ]; then
			echo "Start NAT module ..."
			${PGBIN}/natinit
			echo "NAT module started!"
		fi

		irq_bind
		;;

	*)
		echo "undefined parameter '$2'"
		;;

	esac
fi

if [ "$1" = "stop" ]; then
	target="$2"
	[ "${target}" = "" ] && target="all"

	case "${target}" in
	"httpd")
		httpd_action "stop"
		;;

	"monitor")
		monitor_action "stop"
		;;

	"datamon")
		datamon_action "stop"
		;;

	"xping")
		xping_action "stop"
		;;

	"mgd")
		mgd_action "stop"
		;;

	"panaos")
		panaos_action "stop"
		;;

	"kernel")
		kldunload if_em
		kldunload joskm
		;;

	"appweb")
		appweb_action "stop"
		;;

  # 2013-08-01 add lighttpd web server
	"lighttpd")
		lighttpd_action "stop"
		;;
    
	"all")
		monitor_action "stop"
		httpd_action   "stop"
		appweb_action  "stop"

    # 2013-08-01 add lighttpd web server  
		lighttpd_action "stop"

		datamon_action "stop"
		xping_action   "stop"
		mgd_action     "stop"
		panaos_action  "stop"
		;;

	*)
		echo "undefined parameter '$2' "
		;;
	
	esac
fi

