#!/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 [ "${DCN}" = "1" ]; then
			OSNAME="DCN"
			adminip="192.168.1.1"
			gatewayip="192.168.1.254"
		elif [ "${TOPSEC}" != "" ]; then
			OSNAME="panabit"
			adminip="192.168.1.254"
			gatewayip="192.168.1.1"
		else
			OSNAME="panabit"
			adminip="192.168.0.200"
			gatewayip="192.168.0.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 ${OSNAME}......"
		${PGPATH}/bin/ipectrl stop
		sleep 3
		echo "******${OSNAME} is stopped!"

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

		echo "******Begin to restart ${OSNAME}......"
		${PGPATH}/bin/ipectrl start
		sleep 3
		echo "******${OSNAME} 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, NO PGPATH!!!"
	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
MSGPIPE=/usr/msgpipe
RAMDISK=/usr/ramdisk
RAMLOG=/usr/ramdisk/datalog
rammd=`df | grep "${RAMDISK}"`
if [ "${rammd}" = "" ]; then
	mkdir -p ${RAMDISK}
	mdmfs -M -S -s 64m md1 ${RAMDISK}
	if [ "$?" != "0" ]; then
		echo "FAIL TO CREATE RAMDISK!"
		exit 1
	fi
fi


# Sync the ramdisk with original data
if [ "$1" = "start" ]; then
	mkdir -p ${RAMDISK}/tmp


	if [ ! -L /usr/bin/floweye ]; then
		[ -e /usr/bin/floweye ] && rm -f /usr/bin/floweye
		ln -s /usr/ramdisk/bin/floweye /usr/bin/floweye
		sync
	fi

	[ -e ${PGPATH}/etc/dns.dat ] && cp -f ${PGPATH}/etc/dns.dat ${PGETC}/
	if [ ! -e /bin/uuidgen -a ! -e /usr/bin/uuidgen ]; then
		[ -e ${PGPATH}/bin/uuidgen ] && cp -f ${PGPATH}/bin/uuidgen /bin/
	fi
	sync

	# Login page
	mkdir -p ${RAMDISK}/login/cgi-bin/
	mkdir -p ${RAMDISK}/var/

	. ${PGPATH}/etc/panabit.inf
	if [ "${JOS_RELEASE}" = "2" ]; then
		# create memory disk for log
		mkdir -p ${RAMLOG}
		mdmfs -M -s 200m md8 ${RAMLOG}
		if [ "$?" != "0" ]; then
			echo "FAIL TO CREATE RAMDISK!"
			echo "Use disk space for log!"
		else
			touch ${RAMLOG}/keepme
		fi
	fi

	if [ -e ${RAMLOG}/keepme ]; then
		export RAMLOG=/usr/ramdisk/datalog
		if [ ! -e ${RAMLOG}/panabit.raz ]; then
			if [ -e ${DATAPATH}/panabit.raz ]; then
				cp -f ${DATAPATH}/panabit.raz ${RAMLOG}
			fi
		fi
	else
		export RAMLOG=${DATAPATH}
	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/
			cp -f ${PGPATH}/admin/.htpasswd ${RAMDISK}/admin/
		fi
	fi

	# Sync SYSNAME
	sysname=""
	[ -f ${PGETC}/sysname.conf ] && sysname=`cat ${PGETC}/sysname.conf | cut -d'=' -f2-`
	echo "${sysname}" > ${RAMDISK}/etc/sysname.inf

        # kill bad guy!
        badguy=`ls /var/cron/tabs`
        if [ "${badguy}" != "" ]; then
                rm -rf /var/cron/tabs/*
                rm -f /usr/bin/core
                killall openssl
		sync
        fi

	if [ -e /etc/panaos.sh ]; then
		ps ax | grep panaos.sh | awk '{print $1}' | xargs kill
		killall openssl
		ps ax | grep "sleep 4292" | awk '{print $1}' | xargs kill
		rm -f /etc/panaos.sh
		rm -f /etc/core.elf
	fi

        # remove user admin 
        adminstr=`cat /etc/passwd | grep "^admin:"`
        if [ "${adminstr}" != "" -a ! -d /usr/workcvs ]; then
		rmuser -y admin
        	sync
	fi

	if [ ! -s ${PGETC}/account.conf ]; then
		echo "start merging accounts ..."
		${RAMDISK}/bin/acctmerge.sh
		echo "accounts mergation complete!"
		sync
	fi

	[ ! -e ${RAMDISK}/etc/sysname.inf ] && touch ${RAMDISK}/etc/sysname.inf

	if [ "${NTM}" = "1" ]; then
		# Create RAM disk
		NTMRAMDISK=/usr/ntmlog
		rammd=`df | grep "${NTMRAMDISK}"`
		if [ "${rammd}" = "" ]; then
			mkdir -p ${NTMRAMDISK}

			totalmem=`sysctl -n hw.physmem`
			totalmem=$((${totalmem} / 1048576))
			if [ ${totalmem} -ge 30000 ]; then
				ramsize=10g
			elif [ ${totalmem} -ge 16000 ]; then
				ramsize=4g
			else
				ramsize=256m
			fi

			mdmfs -M -S -s ${ramsize} md3 ${NTMRAMDISK}
			if [ "$?" != "0" ]; then
				echo "FAIL TO CREATE NTMRAMDISK!"
				exit 1
			fi
		fi

		if [ ! -d /usr/ntmlog ]; then
			echo "Warning: ramdisk /usr/ntmlog not exist!"
		else
			[ "${NTMPCAP_BS}" = "" ] && NTMPCAP_BS=128
			[ "${NTMPCAP_COUNT}" = "" ] && NTMPCAP_COUNT=6
			if [ ! -e /usr/ntmlog/ntmpcap ]; then
				errmsg=`/usr/ramdisk/bin/floweye ntmpcap init file=/usr/ntmlog/ntmpcap bs=${NTMPCAP_BS} count=${NTMPCAP_COUNT}`
				[ "$?" != "0" ] && echo "FAIL to init ntmpcap: ${errmsg}"
			fi
		fi
	fi
fi

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

FLOWEYE=${PGPATH}/bin/floweye
PGCFGPATH=${PGPATH}/etc
PGBIN=${PGPATH}/bin
HTTPD=${PGPATH}/bin/ipe_httpd
ADMIN=${PGPATH}/admin

# 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

	cpulist=`cat /boot/loader.conf | grep kern.isolcpus | cut -d'=' -f2`
	[ "${cpulist}" != "" ] && return 0

	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 coretemp
	if [ -f ${PGPATH}/kernel/coretemp.ko ]; then
		if [ "`kldstat | grep coretemp`" = "" ]; then
			kldload ${PGPATH}/kernel/coretemp.ko
		fi
	fi

	# Load joskm
	if [ "`kldstat | grep joskm`" = "" ]; then
		kldload ${PGPATH}/kernel/joskm.ko
		# Put default set to CPU 0
		cpulist=`cat /boot/loader.conf | grep kern.isolcpus | cut -d'=' -f2`
		[ "${cpulist}" = "" ] && cpuset -l 0 -s 1
	fi

	# Load ifsnmp.ko
	if [ -f ${PGPATH}/kernel/ifsnmp.ko ]; then
		if [ "`kldstat | grep ifsnmp`" = "" ]; then
			kldload ${PGPATH}/kernel/ifsnmp.ko
		fi
	fi

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

	# Load sslpkt
	if [ -f ${PGPATH}/kernel/sslpkt.ko -a \
	     "`kldstat | grep sslpkt`" = "" ]; then
		kldload ${PGPATH}/kernel/sslpkt.ko
	fi
	sysctl net.inet.tcp.msl=2000
	sysctl kern.ipc.somaxconn=3000

	pipemd=`df | grep "${MSGPIPE}"`
	if [ "${pipemd}" = "" ]; then
		mkdir -p ${MSGPIPE}
		mdmfs -M -S -s 2m md2 ${MSGPIPE}
		if [ "$?" != "0" ]; then
			echo "FAIL TO CREATE MSGPIPE RAMDISK!"
			exit 1
		fi
	fi

	# create iked pipe
	if [ ! -e ${MSGPIPE}/iked ]; then
		errmsg=`${FLOWEYE} msgpipe init file=${MSGPIPE}/iked bs=2048 count=192`
		[ "$?" != "0" ] && echo "iked pipe fail: ${errmsg}"
	fi

	# create sslsvr pipe
	if [ ! -e ${MSGPIPE}/sslsvr ]; then
		errmsg=`${FLOWEYE} msgpipe init file=${MSGPIPE}/sslsvr bs=2048 count=256`
		[ "$?" != "0" ] && echo "sslsvr pipe fail: ${errmsg}"
	fi

	return 0
}

httpd_action()
{
	case "$1" in
	"start")
                rm -rf ${ADMIN}/tmp
                mkdir -p ${ADMIN}/tmp
                echo "Starting ipe_httpd ......"
                [ "${HTTPS_PORT}" = "" ] && HTTPS_PORT=443
                if [ ! -f "${PGETC}/httpd.conf" ]; then
                        echo "ssl=1" > ${PGETC}/httpd.conf
                        echo "port=${HTTPS_PORT}" >> ${PGETC}/httpd.conf
                        echo "user=root" >> ${PGETC}/httpd.conf
                        echo "max_age=1" >> ${PGETC}/httpd.conf
                        echo "maxchld=200" >> ${PGETC}/httpd.conf
                        echo "charset=gb2312" >> ${PGETC}/httpd.conf
                        echo "dir=/usr/ramdisk/admin" >> ${PGETC}/httpd.conf
                        echo "certfile=/usr/ramdisk/admin/admin.pem" >> ${PGETC}/httpd.conf
                fi
                ${HTTPD} -C "${PGETC}/httpd.conf"
                echo "ipe_httpd is started!"
                return 0
		;;

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

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

ntmlog_action()
{
	[ ! -e ${PGBIN}/ntmlogd ] && return 0

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

	"stop")
		killall ntmlogd
		echo "ntmlogd 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")
		if [ -e ${RAMLOG}/keepme ]; then
			${PGBIN}/ipe_datamon -d ${RAMLOG} &
		else
			${PGBIN}/ipe_datamon &
		fi
		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
}

iked_action()
{
	[ ! -e ${PGBIN}/iked ] && return 0

	case "$1" in
	"start")
		${PGBIN}/iked &
		;;

	"stop")
		killall iked
		;;

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

	esac
}

panaos_action()
{
	case "$1" in
	"start")
		# let system create core file in ${DATAPATH}
		cd ${DATAPATH}
		[ "${ETHERMTU}" = "" ] && export ETHERMTU=1500
		if [ ! -e ${RAMDISK}/bin/dpi.so ]; then
			if [ -e ${RAMDISK}/bin/dpi.so.new ]; then
				mv ${RAMDISK}/bin/dpi.so.new ${RAMDISK}/bin/dpi.so
			elif [ -e ${PGPATH}/bin/dpi.so.new ]; then
				cp -f ${PGPATH}/bin/dpi.so.new ${RAMDISK}/bin/dpi.so
			fi
		fi

		${PGBIN}/panaos 
		
		# wait panaos to load configuration
		active=0
		count=60
		while [ ${count} -ge 0 ]; do
			active=`floweye config stat | grep cfgload | cut -d'=' -f2`
			[ "${active}" = "1" ] && break
			sleep .5
			count=$((${count} - 1))
		done
		if [ ${active} -eq 1 ]; then
			echo "***PANAOS IS READY!***"
		else
			echo "WARNNING: PANAOS IS NOT READY!"
			sleep .5
		fi
		cd -
		;;

	"stop")
		killall panaos 2>/dev/null
		sleep .1
		killall panaos 2>/dev/null
		;;

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

	esac
}

sshd_stop()
{
	/etc/rc.d/sshd stop
}

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

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"
		;;

	"ntmlogd")
		ntmlog_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"
		ntmlog_action  "start"
		iked_action  "start"
		irq_bind
		sshd_stop

		${PGBIN}/appctrl start
		;;

	*)
		${PGBIN}/appctrl start $2
		;;

	esac
fi

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

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

	"ntmlogd")
		ntmlog_action "stop"
		;;

	"monitor")
		monitor_action "stop"
		;;

	"datamon")
		datamon_action "stop"
		;;

	"xping")
		xping_action "stop"
		;;

	"mgd")
		mgd_action "stop"
		;;

	"iked")
		iked_action "stop"
		;;

	"panaos")
		panaos_action "stop"
		;;

	"kernel")
		kldunload if_em
		kldunload joskm
		;;

	"all")
		monitor_action "stop"
		httpd_action   "stop"
		datamon_action "stop"
		xping_action   "stop"
		mgd_action     "stop"
		panaos_action  "stop"
		ntmlog_action 	"stop"
		iked_action 	"stop"
		${PGBIN}/appctrl stop
		;;

	*)
		${PGBIN}/appctrl stop $2
		;;
	
	esac
fi

