#!/usr/bin/bash

main () {
if [ "$UID" -ne "0" ]; then
	echo "Must be run as root"
	exit 1
fi

should_bind_uio=`grep -E "^array_id=(903600|905800)" /boot/loader.conf`
if [ -n "${should_bind_uio}" ]; then
	bind_drv="igb_uio"
else
	bind_drv="vfio-pci"
fi

case $1 in
clear_monitor_key)
	# clear shm keys created by system monitor
	ipcs -m |grep 0xca01e |awk '{system("ipcrm -m "$2)}'
	exit 0
;;
check_nics)
    # TODO: need to support other interface.
    rm -f /ca/conf/af_packet_nic.conf
    if [ -d "/sys/bus/xen/drivers/vif" ]; then
        loops=0
        while [ 1 ]; do
            interface_dir=/sys/bus/xen/drivers/vif/vif-${loops}/net/
            if [ -d "${interface_dir}" ]; then
                interface_name=`ls ${interface_dir}`
                echo ${interface_name} >> /ca/conf/af_packet_nic.conf
                let loops++
                continue
            else
            	break
            fi
        done
    fi
    # Support Hyper-V
    if [ -d "/sys/module/hv_netvsc/drivers/vmbus:hv_netvsc/" ]; then
        loops=0
        while [ ${loops} -le 300 ]; do
            interface_dir=/sys/module/hv_netvsc/drivers/vmbus:hv_netvsc/vmbus_${loops}/net/
            if [ -d "${interface_dir}" ]; then
                interface_name=`ls ${interface_dir}`
                echo ${interface_name} >> /ca/conf/af_packet_nic.conf
            fi
            let loops++
        done
    fi
;;
start_pre)
	#-------------------------start pre--------------------------
	# clean shm and sem created by array
	ipcs -m |grep 0xcaf |awk '{system("ipcrm -m "$2)}'
	ipcs -s |grep 0xcaf |awk '{system("ipcrm -s "$2)}'
	
	# support af_packet on Ustack
	/ca/bin/sysv_click check_nics

	# use system uuid when compute serial number on cloud platform
	system_uuid=`dmidecode -s system-uuid`
	sed -i '/^system_uuid/d' /boot/loader.conf
	echo system_uuid=${system_uuid} >> /boot/loader.conf

	# For 1G/2G/4G machine, enable dynamic hugepage machanism automatically.
	if [ $(is_in_container) -eq 0 ]; then
		memtotal=`grep "MemTotal" /proc/meminfo | awk '{print $2}'`
		if [[ $memtotal -gt 3*1024*1024 && $memtotal -le 4*1024*1024 ]];then
			echo 1024 > /proc/sys/vm/nr_hugepages
			sed -i '/^dynamic_hugepage_enable/d' /boot/loader.conf
			echo "dynamic_hugepage_enable=true" >> /boot/loader.conf
		elif [[ $memtotal -gt 1536*1024 && $memtotal -le 3*1024*1024 ]];then
			echo 512 > /proc/sys/vm/nr_hugepages
			sed -i '/^dynamic_hugepage_enable/d' /boot/loader.conf
			echo "dynamic_hugepage_enable=true" >> /boot/loader.conf
		elif [[ $memtotal -gt 512*1024 && $memtotal -le 1536*1024 ]];then
                        echo 300 > /proc/sys/vm/nr_hugepages
                        sed -i '/^dynamic_hugepage_enable/d' /boot/loader.conf
                        echo "dynamic_hugepage_enable=true" >> /boot/loader.conf
		fi
		echo never > /sys/kernel/mm/transparent_hugepage/enabled
		echo never > /sys/kernel/mm/transparent_hugepage/defrag

		# set linux soft lockup thresh to 30s
		echo 30 > /proc/sys/kernel/watchdog_thresh
	fi

	# create symblink according to current platform.
	/ca/bin/launcher

	# make sure the context is right.
	if selinuxenabled; then
		chcon -t shell_exec_t /ca/bin/ca_shell
		chcon -t shell_exec_t /ca/bin/recovery
		chcon -t sshd_exec_t /ca/bin/sshd
		chcon -t etc_t /var/run/sshd_config
		#add lib_t attribute for /ca/lib and its files, else the ldconfig will fail to run in systmed.
		chcon -R -t lib_t /ca/lib
	fi

	# creat veth pair for localhost communication
	ip link add dev dpdk_veth0 type veth peer name dpdk_veth1
	ip link set dev dpdk_veth0 up
	ip link set dev dpdk_veth1 up
	ip addr add 192.0.0.2/24 dev dpdk_veth1
	ethtool -K dpdk_veth1 tso off

	# run the ldconfig, make sure the db updated.
	/usr/sbin/ldconfig

	if [ $(is_in_container) -eq 0 ]; then
		# install the needed kmod
		if [ ${bind_drv} = "vfio-pci" ]; then
			vfio_pci=`grep "^vfio_pci" /proc/modules`
			if [ ! -z "${vfio_pci}" ]; then
				echo "Already install kmod vfio_pci"
			else
				if [ -d "/sys/class/iommu/dmar0" ]; then
								echo "vfio-iommu"
								modprobe vfio
						else
								echo "vfio-noiommu"
								modprobe vfio enable_unsafe_noiommu_mode=Y
						fi
				modprobe vfio-pci
				vfio_pci=`grep "^vfio_pci" /proc/modules`
				if [ -z "${vfio_pci}" ]; then
					echo "failed to install kmod vfio_pci"
					exit 2
				fi
			fi
		else
			uio_driver=`grep "^igb_uio" /proc/modules`
			if [ ! -z "${uio_driver}" ]; then
				echo "Already install kmod igb_uio"
			else
				modprobe uio
				insmod /ca/kmod/igb_uio.ko
				uio_driver=`grep "^igb_uio" /proc/modules`
				if [ -z "${uio_driver}" ]; then
					echo "failed to install kmod igb_uio"
					exit 2
				fi
			fi
		fi

		vhost_net=`grep "^vhost_net" /proc/modules`
		if [ ! -z "${vhost_net}" ]; then
			echo "Already install kmod vhost_net"
		else
			modprobe vhost_net
			vhost_net=`grep "^vhost_net" /proc/modules`
			if [ -z "${vhost_net}" ]; then
				echo "failed to install kmod vhost_net"
				exit 3
			fi
		fi

		# bind vfio_pci|uio_pci_generic
		nics=`/ca/bin/dpdk-devbind.py --status  | grep "drv=${bind_drv}" -v | \
			grep "^[0-9]" | grep "\*Active\*" -v `
		IFS=' '
		driver_arr=(${nics})
		# check PCI stub driver, until unbind interface is ready
		for i in ${driver_arr[@]}
		do
			if [[ $i =~ ^drv= ]];then
				timeout=30
				until [ -e /sys/bus/pci/drivers/${i##drv=}/unbind ] || [ $((timeout--)) -eq 0 ]
				do
					sleep 1
				done
			fi
		done
		if [ ! -z "${driver_arr}" ]; then
			/ca/bin/dpdk-devbind.py --status  | grep "drv=${bind_drv}" -v | \
				grep "^[0-9]" | grep "\*Active\*" -v | cut -d " " -f1 | \
				xargs /ca/bin/dpdk-devbind.py --bind=${bind_drv}
		fi

		# install conntrack related kmod
		modprobe nf_conntrack
		modprobe nf_conntrack_netlink
		modprobe nf_conntrack_ipv4
		modprobe nf_conntrack_ipv6

        	# If it is a hardware ustack, enable ipmi_watchdog module at default.
        	manufact=`dmidecode -s system-manufacturer`
        	if [[ ${manufact} =~ "Supermicro" ]]; then
			ret=`lsmod|grep ipmi_watchdog`
			if [ -z "$ret" ]; then
                		echo "ipmi_watchdog" > /etc/modules-load.d/ipmi_wdt.conf
                		modprobe ipmi_watchdog
			fi
        	fi 

        	# check watchdog.service status if there are a character file /dev/watchdog.
        	if [ -c /dev/watchdog ]; then
			# make sure watchdog.service is enabled.
			systemctl -q is-enabled watchdog > /dev/null
			if [ $? -ne 0 ]; then
				systemctl enable watchdog > /dev/null
			fi 
			systemctl -q is-active watchdog > /dev/null
			if [ $? -ne 0 ]; then
				systemctl start watchdog > /dev/null
			fi
		fi 
	fi

	if [ ! -f "/lib64/libnfnetlink.so" ]; then
		ln -s /lib64/libnfnetlink.so.0.2.0 /lib64/libnfnetlink.so
	fi
	if [ ! -f "/lib64/libnetfilter_conntrack.so" ]; then
		ln -s /lib64/libnetfilter_conntrack.so.3.5.0 /lib64/libnetfilter_conntrack.so
	fi
	
	if [ ! -e "/var/crash/fsys_" ]; then
		ln -sf /var/crash/fsys_d /var/crash/fsys_
	elif [ -L "/var/crash/fsys_/fsys_d" ]; then
		rm /var/crash/fsys_/fsys_d
	fi

	if [ ! -f "/var/crash/sshd_login_msgq" ]; then
		touch "/var/crash/sshd_login_msgq"
	fi
	
	# for uproxy rewrite ; it has to run before backend
	if [ -f /ca/conf/proxy_html_def.conf ]; then
        	cp /ca/conf/proxy_html_def.conf /var/run/proxy_html.conf 
	fi
	
	if [ -f /ca/conf/rewrite_config_test.pl ]; then
        	cp /ca/conf/rewrite_config_test.pl /ca/bin/
	fi

	if [ ! -d "/var/run/waf" ]; then
		mkdir -p "/var/run/waf"
	fi
	
	if [ ! -d /etc/usercfg/ca/conf/waf/custom ]; then
		mkdir -p /etc/usercfg/ca/conf/waf/custom
	fi

	if [ ! -d /ca/conf/kerberos ]; then
		mkdir -p /ca/conf/kerberos
	fi

	if [ -f /ca/conf/mod_security2_def.conf ]; then
        	cp /ca/conf/mod_security2_def.conf /var/run/waf/mod_security2_def.conf
	fi

	if [ -f /ca/conf/mlogc-default.conf ]; then
        	cp /ca/conf/mlogc-default.conf /var/run/waf/mlogc-default.conf
	fi

	if [ -f /ca/conf/modsec_config.pl ]; then
        	cp /ca/conf/modsec_config.pl /ca/bin/
	fi

	if [ ! -d "/var/spool/clientmqueue" ]; then
		mkdir -p "/var/spool/clientmqueue"
		chown -R smmsp:smmsp /var/spool/clientmqueue
	fi

	if [ ! -d "/var/spool/mqueue" ]; then
		mkdir -p "/var/spool/mqueue"
		chown -R root:mail /var/spool/mqueue
	fi

	/ca/bin/atcp_config
	
	if [ $(is_in_container) -eq 0 ]; then
		# bug66058
		auditctl -b 8192

		# disable ASLR before ATCP start
		echo 0 > /proc/sys/kernel/randomize_va_space
	fi

	systemctl restart systemd-journald

	echo "Begin to run eventlogd......"
	if [ -x /ca/bin/eventlogd ]; then
        /ca/bin/sysmon -c "/ca/bin/eventlogd" -l "/var/crash/ca_log/eventlogd.log"
        echo "Succeed to run eventlogd......"
	else
		echo "Failed to run eventlogd......"
	fi
        #for ntp
        if [ -f "/etc/hosts" ]; then
                grep localhost.localdomain /etc/hosts > /dev/null
                if [ $? -eq 0 ]; then
                        sed -i 's/localhost.localdomain/localhost/' /etc/hosts
                else
                        echo "127.0.0.1 localhost" >> /etc/hosts
                fi
        fi
        if [ -f "/ca/etc/upgrade.deferred" ]; then
                rm -f /ca/etc/upgrade.deferred
        fi
	#bug 17787
	echo "Begin to configure default ip address......"
	array_id=`grep "array_id" /boot/loader.conf | cut -d "=" -f 2`
	if [ "$array_id" != "900000" ]; then
		default_ipaddr=192.168.1.200
		IPADDR=`awk '/^ip address/' /ca/conf/ca.conf`
		if [ -z "$IPADDR" ]; then
			if [ ! -e /ca/conf/ca.conf ]; then
				/bin/echo "#ip configuration" > /ca/conf/ca.conf
				/bin/sync
			fi

			if [ -e /ca/conf/ca.conf ]; then
				ifname=`awk '/^interface name "port1"/ {print substr($0, 24, length($0)-23)}' /ca/conf/ca.conf`
				/bin/echo "ip address $ifname $default_ipaddr 255.255.255.0" >> /ca/conf/ca.conf

				/bin/echo "#webui configuration" >> /ca/conf/ca.conf
				/bin/echo "webui port 8888" >> /ca/conf/ca.conf
				/bin/echo "webui on" >> /ca/conf/ca.conf
				/bin/echo "Create IP:$default_ipaddr to the $ifname interface, turn WebUI on"
			fi
		fi
	fi
	echo "Succeed to configure default ip address......"
	#bug 17787 end
;;
start)
	#check ustack status
	echo "Checking Ustack's status......"
	loops=0
	while [ ${loops} -lt 10 ]; do
		is_clear=`/ca/bin/sysmon -C | awk '{print $1}'`
		if [ "${is_clear}" == "Clear" ]; then
			echo "Ustack off, can start it"
			break;
		else
			let loops++
			sleep 1
			continue
		fi
	done

	if [ ${loops} -ge 10 ]; then
		echo "Ustack is running, please do not run it again."
		exit
	else
		#start pre
		/ca/bin/sysv_click start_pre

		#-------------------------start atcp--------------------------
		echo "Begin to run atcp......"
		/ca/bin/sysmon -c /ca/bin/atcp -n -R -l "/var/crash/ca_log/atcp.log"

		echo "Atcp initializing......"
		#check whether atcp ready or not
		is_atcp_ready=`/ca/bin/sysv_click atcp_ready| awk '{print $4}'`

		#if atcp is up, then start userland process
		if [ "${is_atcp_ready}" == "up" ]; then
			echo "Succeed to run atcp......"

			#start post
			/ca/bin/sysv_click start_post
		fi
	fi
;;
start_post)
	#-------------------------start post--------------------------
	# bug 75635
	systemctl restart firewalld
	if [ $(is_in_container) -eq 0 ]; then
		# enable ASLR after ATCP started
		echo 2 > /proc/sys/kernel/randomize_va_space

		# prevent atcp & va process from being killed by linux OOM killer.
		pgrep -f "atcp$|va$" | while read PID; do 
				echo -17 > /proc/${PID}/oom_adj;
				echo 0x7f > /proc/${PID}/coredump_filter
		done

		# check firewalld configs
		#rule for vrrp
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol vrrp -j ACCEPT
		firewall-cmd --direct --add-rule ipv6 filter INPUT 0 --protocol vrrp -j ACCEPT
		#rule for snmp
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol udp --dport 161 -j ACCEPT
		firewall-cmd --direct --add-rule ipv6 filter INPUT 0 --protocol udp --dport 161 -j ACCEPT
		#rule for bgp
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol tcp --dport 179 -j ACCEPT
		firewall-cmd --direct --add-rule ipv6 filter INPUT 0 --protocol tcp --dport 179 -j ACCEPT
		#rule for rip
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol udp --dport 520 -j ACCEPT
		#rule for ospf
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol ospf -j ACCEPT
		firewall-cmd --direct --add-rule ipv6 filter INPUT 0 --protocol ospf -j ACCEPT
		#rule for nginx
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol tcp --dport 65521 -j ACCEPT
		firewall-cmd --direct --add-rule ipv6 filter INPUT 0 --protocol tcp --dport 65521 -j ACCEPT
		#rule for synconfig
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol tcp --dport 65519 -j ACCEPT
		firewall-cmd --direct --add-rule ipv6 filter INPUT 0 --protocol tcp --dport 65519 -j ACCEPT
		#rule for tftp-client
		firewall-cmd --add-service=tftp-client
		#rule for localhost communication
		firewall-cmd --direct --add-rule ipv4 filter INPUT 0 --protocol ip --source 192.0.0.1 -j ACCEPT
	fi

	#Close Xen platform interface(ethx, atcp_vethx) gro
        if [ -d "/sys/bus/xen/drivers/vif/vif-0/net/" ];then
                eths_arr=(`ip addr | awk '{print $2}'| grep "eth" | grep "dpdk" -v`)
                for i in ${eths_arr[@]}
                do
                        if [[ $i =~ ^eth || $i =~ ^atcp_veth ]];then
                                ethtool -K ${i%%:} gro off
                        fi
                done

        fi

	#-------------------------start userland process--------------------------
	echo "Begin to run sessmgrd......"
        if [ -x /ca/bin/sessmgrd ]; then
                /ca/bin/sysmon -c "/ca/bin/sessmgrd" -l "/var/crash/ca_log/sessmgrd.log"
                echo "Succeed to run sessmgrd......"
        else
                echo "Failed to run sessmgrd......"
        fi

        echo "Begin to run aaad......"
        if [ -x /ca/bin/aaad ]; then
                /ca/bin/sysmon -c "/ca/bin/aaad" -l "/var/crash/ca_log/aaad.log"
                echo "Succeed to run aaad......"
        else
                echo "Failed to run aaad......"
        fi

	echo "Begin to run feactlinit......"
	if [ -x /ca/bin/feactlinit ]; then
		/ca/bin/feactlinit
		echo "Succeed to run feactlinit......"
	else
		echo "Failed to run feactlinit......"
	fi

	echo "Begin to run tracker......"
	if [ -x /ca/bin/tracker ]; then
		/ca/bin/sysmon -c "/ca/bin/tracker" -l "/var/crash/ca_log/tracker.log"
		echo "Succeed to run tracker......"
	else
		echo "Failed to run tracker......"
	fi

	echo "Begin to run cert......"
	if [ -x /ca/bin/cert ]; then
		/ca/bin/sysmon -c "/ca/bin/cert" -r "/ca/bin/cert -r" -l "/var/crash/ca_log/cert.log"
		echo "Succeed to run cert......"
	else
		echo "Failed to run cert......"
	fi

	echo "Begin to run check_mainboard......"
	if [ -x /ca/bin/check_mainboard ]; then
		/ca/bin/sysmon -c "/ca/bin/check_mainboard" -l "/var/crash/ca_log/check_mainboard.log"
		echo "Succeed to run check_mainboard......"
	else
		echo "Failed to run check_mainboard......"
	fi

	echo "Begin to run VA......"
	if [ -x /ca/bin/va ]; then
		/ca/bin/sysmon -c "/ca/bin/va" -R -l "/var/crash/ca_log/va.log"
		echo "Succeed to run VA......"
	else
		echo "Failed to run VA......"
	fi

	echo "Begin to run backend......"
	if [ -x /ca/bin/backend ]; then
		#print the message to tell the user to wait for loading configuration
		echo "Loading configuration, please wait ......"
		/ca/bin/sysmon -c "/ca/bin/backend" -l "/var/crash/ca_log/backend.log"
		echo "Succeed to run backend......"
	else
		echo "Failed to run backend......"
	fi

	echo "Begin to run hc_daemon......"
	if [ -x /ca/bin/hc_daemon ]; then
		/ca/bin/sysmon -c "/ca/bin/hc_daemon" -l "/var/crash/ca_log/hc_daemon.log"
		echo "Succeed to run hc_daemon......"
	else
		echo "Failed to run hc_daemon......"
	fi

	echo "Begin to run global_monitord......"
	if [ -x /ca/bin/global_monitord ]; then
		/ca/bin/sysmon -c "/ca/bin/global_monitord" -l "/var/crash/ca_log/global_monitord.log"
		echo "Succeed to run global_monitord......"
	else
		echo "Failed to run global_monitord......"
	fi

	echo "Begin to run ha_domain......"
	if [ -x /ca/bin/ha_domain ]; then
		/ca/bin/sysmon -c "/ca/bin/ha_domain" -l "/var/crash/ca_log/ha_domain.log"
		echo "Succeed to run ha_domain......"
	else
		echo "Failed to run ha_domain......"
	fi

	echo "Begin to run decisiond......"
	if [ -x /ca/bin/decisiond ]; then
		/ca/bin/sysmon -c "/ca/bin/decisiond" -l "/var/crash/ca_log/decisiond.log"
		echo "Succeed to run decisiond......"
	else
		echo "Failed to run decisiond......"
	fi

	echo "Begin to run llb_hc_daemon......"
	if [ -x /ca/bin/llb_hc_daemon ]; then
		/ca/bin/sysmon -c "/ca/bin/llb_hc_daemon" -l "/var/crash/ca_log/llb_hc_daemon.log"
		echo "Succeed to run llb_hc_daemon......"
	else
		echo "Failed to run llb_hc_daemon......"
	fi

	echo "Begin to run dd_daemon......"
	if [ -x /ca/bin/dd_daemon ]; then
		/ca/bin/sysmon -c "/ca/bin/dd_daemon" -l "/var/crash/ca_log/dd_daemon.log"
		echo "Succeed to run dd_daemon......"
	else
		echo "Failed to run dd_daemon......"
	fi

	echo "Begin to run wwlogd......"
	if [ -x /ca/bin/wwlogd ]; then
		/ca/bin/sysmon -c "/ca/bin/wwlogd" -l "/var/crash/ca_log/wwlogd.log"
		echo "Succeed to run wwlogd......"
	else
		echo "Failed to run wwlogd......"
	fi

	echo "Begin to run domain_eroute_daemon......"
	if [ -x /ca/bin/domain_eroute_daemon ]; then
		/ca/bin/sysmon -c "/ca/bin/domain_eroute_daemon" -l "/var/crash/ca_log/domain_eroute_daemon.log"
		echo "Succeed to run domain_eroute_daemon......"
	else
		echo "Failed to run domain_eroute_daemon......"
	fi

	echo "Begin to run monitord......"
	if [ -x /ca/bin/monitord ]; then
		/ca/bin/sysmon -c "/ca/bin/monitord" -l "/var/crash/ca_log/monitord.log"
		echo "Succeed to run monitord......"
	else
		echo "Failed to run monitord......"
	fi

	echo "Begin to run SdnsApp......"
	if [ -x /ca/bin/SdnsApp ]; then
		/ca/bin/sysmon -c "/ca/bin/SdnsApp" -r "/ca/bin/sdns_recover.sh" -l "/var/crash/ca_log/SdnsApp.log"
		echo "Succeed to run SdnsApp......"
	else
		echo "Failed to run SdnsApp......"
	fi

	echo "Begin to run webui_agent......"
	if [ -x /ca/bin/webui_agent ]; then
		/ca/bin/sysmon -c "/ca/bin/webui_agent" -l "/var/crash/ca_log/webui_agent.log"
		echo "Succeed to run webui_agent......"
	else
		echo "Failed to run webui_agent......"
	fi

	echo "Begin to run snmpinfod......"
	if [ -x /ca/bin/snmpinfod ]; then
		/ca/bin/sysmon -c "/ca/bin/snmpinfod" -l "/var/crash/ca_log/snmpinfod.log"
		echo "Succeed to run snmpinfod......"
	else
		echo "Failed to run snmpinfod......"
	fi

	echo "Begin to run nginx......"
	if [ -x /ca/bin/nginx ]; then
		/ca/bin/sysmon -c "/ca/bin/nginx" -l "/var/crash/ca_log/nginx.log"
		echo "Succeed to run nginx......"
	else
		echo "Failed to run nginx......"
	fi

	#mkdir for new webui graph files
	if [ ! -d /var/crash/graphdb ]; then
        	mkdir -p /var/crash/graphdb
       		chmod -R 755 /var/crash/graphdb
	fi

	#mkdir for bind9 configure file and zone files
	if [ ! -d /etc/usercfg/etc/namedb/zone ]; then
		mkdir -p /etc/usercfg/etc/namedb/zone
	fi

	if [ ! -d /var/crash/proxy ]; then
		mkdir -p /var/crash/proxy
	fi

	if [ ! -d /var/log/waf/concurrent_audit/data ]; then
		mkdir -p /var/log/waf/concurrent_audit/data
	fi

	if [ ! -d "/var/crash/fsys_d/ssl/vhost" ]; then
		mkdir -p "/var/crash/fsys_d/ssl/vhost"
	fi

	if [ ! -d "/var/backups" ]; then
		mkdir -p "/var/backups"
	fi

	if [ ! -d "/var/log/xmlrpc.ssl_mutex" ]; then
		mkdir -p "/var/log/xmlrpc.ssl_mutex"
	fi

	if [ ! -d "/var/crash/statmon" ]; then
		mkdir -p "/var/crash/statmon"
	fi

	if [ -d /ca/conf/waf ]; then
		cp -rf /ca/conf/waf /var/run/
	fi

	#TODO
	#if [ -x /ca/bin/http_filter_d ]; then 
	#	chmod -R 777 /var/run/waf/custom
	#	touch /var/log/waf/debug.log
	#	chmod -R 777 /var/log/waf/
	#	/ca/bin/syslog_wheel.sh /var/log/waf/debug.log &
	#fi

	echo "Begin to run diskfreed......"
	if [ -x /ca/bin/diskfreed ]; then
		/ca/bin/sysmon -c "/ca/bin/diskfreed" -l "/var/crash/ca_log/diskfreed.log"
		#/ca/bin/diskfreed &
		echo "Succeed to run diskfreed......"
	else
		echo "Failed to run diskfreed......"
	fi

	echo "Begin to create dirs which used by webui graph......"
	if [ -x /ca/bin/statmond ]; then
		mkdir -p /var/crash/statmon
		chmod 0755 /var/crash
		chmod 0755 /var/crash/statmon
        rm -rf /var/run/graphs
        mkdir /var/run/graphs
        chmod 1777 /var/run/graphs
	fi

	#webui_fcgi.service
	#echo "Begin to run python......"
	#if [ -x /usr/bin/python ]; then
	#	/ca/bin/sysmon -c "/usr/bin/python /ca/webui/htdocs/new/src/manage.py runfcgi method=threaded host=127.0.0.1 daemonize=false port=3033 webui_on" -l "/var/crash/ca_log/python.log"
	#	echo "Succeed to run python......"
	#else
	#	echo "Failed to run python......"
	#fi

	/ca/bin/sysv_click avx_vtch
;;
atcp_ready)
	loops=0
	while [ ${loops} -lt 300 ]; do
		# first, check the atcp process have create ioctl_handler thread.
		atcp_pid=`ps -C atcp -o pid=`
		if [ $? -ne 0 ];then
			let loops++
			sleep 1
			continue
		fi
		ready=`top -bn 1 -w 256 -H -p ${atcp_pid} | grep ioctl_handler`
		if [ -z "${ready}" ]; then
			let loops++
			sleep 1
			continue
		fi

		# second, check the atcp process have create sysctl_handler thread.
		ready=`top -bn 1 -w 256 -H -p ${atcp_pid} | grep sysctl_handler`
		if [ -z "${ready}" ]; then
			let loops++
			sleep 1
			continue
		fi
		# third, check all the atcp thread done initialization.
		ready=`/ca/bin/u_sysctl net.inet.clicktcp.thread_init | awk '{print $2}'`
		if [  ${ready} -eq 1 ]; then
			echo "Atcp program started up"
			break
		else
			let loops++
			sleep 1
		fi
        done
;;
atcp_exit)
	loops=0
	while [ ${loops} -lt 300 ]; do
		#get pid of process atcp
		atcp_pid=`ps -C atcp -o pid=`
		if [ -n "${atcp_pid}" ]; then
			let loops++
			sleep 1
			continue
		else
			echo "Atcp exit"
			break
		fi
	done
;;
avx_vtch)
	# starting avx2.0 virt channel service
	model_name=`/ca/bin/u_sysctl  -n kern.model_name`
	if [ "$model_name" = "AFM_MODEL_vAPV" ]; then
		echo "Begin to run avx_vtch......"
        	if [ -x /ca/bin/avx_vtch ]; then
                	/ca/bin/avx_vtch &
        	fi
	fi
;;
avx_vtch_stop)
	shoot avx_vtch
;;
stop)
	#stop all processes in system monitor
	/ca/bin/sysmon -S
	echo "Stopped all processes in system monitor"
	
	#need to kill child backend
	echo "Prepare to kill child backend......"
	killall -9 backend
	echo "Stopped child backend"

	#need to kill /ca/bin/tcpdump if exist.
	killall /ca/bin/tcpdump > /dev/null 2>&1

	echo "Waiting for atcp exit......"
	#check whether atcp exit or not
	is_atcp_exit=`/ca/bin/sysv_click atcp_exit| awk '{print $2}'`

	if [ "${is_atcp_exit}" == "exit" ]; then
		echo "Atcp exit succussfully"
		/ca/bin/sysv_click stop_post
	else
		echo "Atcp did't exit succussfully"
	fi
;;
stop_post)
	ip link del dpdk_veth0

	if [ $(is_in_container) -eq 0 ]; then
		rm -rf /tmp/fastlog.sock
		/ca/bin/dpdk-devbind.py --status  | grep "drv=${bind_drv}" | \
			cut -d " " -f1 | xargs /ca/bin/dpdk-devbind.py --unbind
		
		if [ ${bind_drv} = "vfio-pci" ]; then
			rmmod vfio_pci
			rmmod vfio_iommu_type1
			rmmod vfio
		else
			rmmod igb_uio
			rmmod uio
		fi

		modprobe -r vhost_net

		#rule for vrrp
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol vrrp -j ACCEPT
		firewall-cmd --direct --remove-rule ipv6 filter INPUT 0 --protocol vrrp -j ACCEPT
		#rule for snmp
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol udp --dport 161 -j ACCEPT
		firewall-cmd --direct --remove-rule ipv6 filter INPUT 0 --protocol udp --dport 161 -j ACCEPT
		#rule for bgp
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol tcp --dport 179 -j ACCEPT
		firewall-cmd --direct --remove-rule ipv6 filter INPUT 0 --protocol tcp --dport 179 -j ACCEPT
		#rule for rip
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol udp --dport 520 -j ACCEPT
		#rule for ospf
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol ospf -j ACCEPT
		firewall-cmd --direct --remove-rule ipv6 filter INPUT 0 --protocol ospf -j ACCEPT
		#rule for nginx
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol tcp --dport 65521 -j ACCEPT
		firewall-cmd --direct --remove-rule ipv6 filter INPUT 0 --protocol tcp --dport 65521 -j ACCEPT
		#rule for synconfig
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol tcp --dport 65519 -j ACCEPT
		firewall-cmd --direct --remove-rule ipv6 filter INPUT 0 --protocol tcp --dport 65519 -j ACCEPT
		#rule for tftp-client
		firewall-cmd --remove-service=tftp-client
		#rule for localhost communication
		firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 --protocol ip --source 192.0.0.1 -j ACCEPT
	fi

	#"system reboot" or "system update", need remove watchdog
	ret=`lsmod|grep ipmi_watchdog`
	if [ -n "$ret" ]; then
		systemctl -q is-active watchdog > /dev/null
		if [ $? -eq 0 ]; then
			systemctl stop watchdog > /dev/null
		fi
		rmmod ipmi_watchdog 
	fi

	/ca/bin/sysv_click avx_vtch_stop
;;
restart)
	/ca/bin/sysv_click stop
	/ca/bin/sysv_click start
;;
reboot)
	/ca/bin/sysv_click stop
	reboot
;;
status)
	atcp_pid=`ps -C atcp -o pid=`
	if [ $? -ne 0 ];then
		echo "Ustack off"
	else
		echo "Ustack on"
	fi
;;
coredump_on)
	#We have set "ulimit - c 0" in rc.local and all arrayOS proc will inherit it.
	#We can set core_pattern value start as "|" to open arrayOS proc coredump
        echo "|/ca/bin/sysv_click core_helper %E %p %t" > /proc/sys/kernel/core_pattern
;;
coredump_off)
	#Set core_pattern value no "|" to close arrayOS proc coredump
	#Other proc not in arrayOS coredump file will be /var/crash/%e_%p_%t.core
        echo "/var/crash/%e_%p_%t.core" > /proc/sys/kernel/core_pattern
;;
core_helper)
	if [ $# != 4 ];then
		echo "Incorrect argument"
		exit 1
	fi
	ctime=`date --date=@$4 +%G.%m.%d-%T`
	cmd=${2##*!}
	# Notice each logined user, generated a corefile.
	`grep COREFILE_PROMPT=1 /etc/profile`
	if [ $? -eq 0 ];then
		wall "INFO: Generating a corefile \"$cmd-$3-$ctime.core.gz\""
	fi
	exec gzip - > /var/crash/$cmd-$3-$ctime.core.gz
;;
fallback)
	touch /var/spool/upgrade/fallback_pending
;;
*)
	echo "Usage : $0 {start | start_pre | start_post | restart | stop | stop_post | atcp_ready | atcp_exit | clear_monitor_key }"
	exit 1
esac
} ## end of main function

# shoot targe process 
function shoot () {
	pids=`ps -C ${1} -o pid=`
	for pid in ${pids}
	do 
		kill -9 ${pid}
	done
}

# Docker container detector
function is_in_container() {
	ret=`mount | grep docker`
	if [ -z "$ret" ]; then
		echo 0;
	else
		echo 1;
	fi
	
}

main $@
