#!/bin/bash
#
# tcp_toa
#
# chkconfig: 2345 20 80
# description: CTYUN CDN TOA
#
# processname: tcp_toa
#

# Source system profile
. /etc/profile

# process monitor
WORK_PATH="/usr/local/tcp_toa/"
PROGRAM="tcp_toa"
MODULE_NAME="tcp_toa"

function print_ok()
{
	echo -e "\t\\033[0;32m[OK]\\033[0m"
}

function print_warn()
{
	echo -e "\t\\033[0;33m[WARNING]\\033[0m"
}

function print_failed()
{
	echo -e "\t\\033[0;31m[FAILED]\\033[0m"
}

function check_install()
{
	local not_installed
	local retcode

	lsmod | grep -q "^${MODULE_NAME} "
	retcode=$?
	not_installed=$retcode

	return $not_installed
}

function install_modules()
{
	local retcode

	if [ -f "${WORK_PATH}/${MODULE_NAME}.ko" ]; then
		echo -ne "installing ${MODULE_NAME}...\t\t"
		insmod "${WORK_PATH}/${MODULE_NAME}.ko" 2>&1 >/dev/null
		retcode=$?
		if [ $retcode -ne 0 ]; then
			echo -ne "\treturn: ${retcode}"
			print_failed
			return 1
		else
			print_ok
		fi
	else
		print_failed
		return 1
	fi

	return 0
}

function uninstall_modules()
{
	local retcode

	lsmod | grep -q "^${MODULE_NAME} "
	if [ $? -eq 0 ]; then
		echo -ne "uninstalling ${MODULE_NAME}...\t\t"
		rmmod $MODULE_NAME
		retcode=$?
		if [ $retcode -ne 0 ]; then
			echo -ne "\treturn: ${retcode}"
			print_failed
		else
			print_ok
		fi
	fi

	# always success
	return 0
}

function start()
{
	echo "[starting ${PROGRAM}]:"

	check_install
	if [ $? -eq 0 ]; then
		echo -ne "${PROGRAM} is running!\t\t"
		print_warn
		return 1
	fi

	install_modules
	if [ $? -ne 0 ]; then
		stop
		return 1
	fi
}

function stop()
{
	echo "[stopping ${PROGRAM}]:"

	check_install
	if [ $? -ne 0 ]; then
		echo -ne "${PROGRAM} is not running!\t\t"
		print_ok
		return 0
	fi

	uninstall_modules
}

case $1 in
	start)
		start
		;;
	stop)
		stop
		;;
	*)
		echo "usage $0 {start|stop}"
		exit 1
		;;
esac

