#!/bin/bash

MYLOGFILE=box_System_ipmi
CONFIG=/opt/phion/config/active/boxsys.conf

if [ -f /etc/phion/functions ]; then
	source /etc/phion/functions
	logerror="LogError ${MYLOGFILE}"
else
	logerror=echo
fi

function loadKernelModules {
	if [ ! -e /dev/ipmi0 ]; then
		$logerror "Info" "loading IPMI kernel drivers"
		modprobe ipmi_si
		modprobe ipmi_msghandler
		modprobe ipmi_devintf

		for i in $(seq 1 5)
		do
		if [ -e /dev/ipmi0 ]; then
			$logerror "Info" "IPMI kernel drivers loaded successfully"
			return 0
		fi
		usleep 500000
		done

		$logerror "Error" "unable to load IPMI kernel driver modules - please look into box_System_klog.log"
		return 1
	fi
}

function unloadKernelModules {
	modprobe -r ipmi_devintf
	modprobe -r ipmi_si
	modprobe -r ipmi_msghandler
}

function execlog {
	if [ "_$2" != "_" ]; then
		$logerror "Info" "$2"
	fi
	local -r RESULT=`$1 2>&1 > /dev/null|head -n1`
	if [ "$RESULT" ]; then
		$logerror "Error" "$2: $RESULT"
		$logerror "Error" "fatal error occurred, disabling remote IPMI access"
		local -r RESULT2=`ipmitool lan set 1 access off 2>&1 > /dev/null|head -n1`
		if [ "$RESULT2" ]; then
			$logerror "Error" "failed to disable remote IPMI access: $RESULT2"
		fi
		exit
	fi
}

function configureDynamicAddress {
	execlog "ipmitool lan set 1 ipsrc dhcp" "setting IPMI address source to dynamic" "failed to set IPMI address source"
	execlog "ipmitool lan set 1 access on" "enabling remote IPMI access" "failed to enable remote IPMI access"
}

function configureStaticAddress {
	local IP=`boxinfo config $CONFIG ipmi ipmiaddress 2> /dev/null`
	local MASK=`boxinfo config $CONFIG ipmi ipmimask 2> /dev/null`
	local GW=`boxinfo config $CONFIG ipmi ipmigw 2> /dev/null`
	local GWMAC=`boxinfo config $CONFIG ipmi ipmigwmac 2> /dev/null`

	if [ -z "$GWMAC" ]; then
		GWMAC="00:00:00:00:00:00"
	fi

	local OLDIP=`ipmitool lan print 1|grep "IP Address[[:space:]]*:"|awk 'BEGIN { FS=": " } { print $2; }'`
	local OLDMASK=`ipmitool lan print 1|grep "Subnet Mask[[:space:]]*:"|awk 'BEGIN { FS=": " } { print $2; }'`
	local OLDGW=`ipmitool lan print 1|grep "Default Gateway IP[[:space:]]*:"|awk 'BEGIN { FS=": " } { print $2; }'`
	local OLDGWMAC=`ipmitool lan print 1|grep "Default Gateway MAC[[:space:]]*:"|awk 'BEGIN { FS=": " } { print $2; }'`

	execlog "ipmitool lan set 1 ipsrc static" "setting IPMI address source to static" "failed to set IPMI address source"

	if [ "_$IP" != "_$OLDIP" ]; then
		execlog "ipmitool lan set 1 ipaddr $IP" "setting IPMI address to $IP" "failed to set IPMI address"
	fi

	if [ "_$MASK" != "_$OLDMASK" ]; then
		execlog "ipmitool lan set 1 netmask $MASK" "setting IPMI netmask to $MASK" "failed to set IPMI mask"
	fi

	if [ "_$GW" != "_$OLDGW" ]; then
		execlog "ipmitool lan set 1 defgw ipaddr $GW" "setting IPMI default gateway to $GW" "failed to set IPMI default gateway"
	fi

	if [ "_$GWMAC" != "_$OLDGWMAC" ]; then
		execlog "ipmitool lan set 1 defgw macaddr $GWMAC" "setting IPMI default gateway MAC to $GWMAC" "failed to set IPMI default gateway MAC"
	fi

	execlog "ipmitool lan set 1 access on" "enabling remote IPMI access" "failed to enable remote IPMI access"
}

function setAuth {

	# enforce MD5 for IPMI 1.5
	execlog "ipmitool lan set 1 auth Callback MD5" "setting required authentication to MD5 for Callback" "failed to set authentication method"
	execlog "ipmitool lan set 1 auth User MD5" "setting required authentication to MD5 for User" "failed to set authentication method"
	execlog "ipmitool lan set 1 auth Admin MD5" "setting required authentication to MD5 for Admin" "failed to set authentication method"
	execlog "ipmitool lan set 1 auth Operator MD5" "setting required authentication to MD5 for Operator" "failed to set authentication method"

	# enforce secure cipher suites for IPMI 2.0 - requires authentication, integrity checking and encryption better than RC4
	execlog "ipmitool lan set 1 cipher_privs XXXaXXXXaXXXXXX" "setting IPMI 2.0 cipher suites" "failed to set IPMI 2.0 cipher suites"
}

function disableAllUsers {
	for USERID in `ipmitool user list 1 | awk 'NR > 1 { print $1; }'`
	do
		execlog "ipmitool user disable $USERID" "disabling user $USERID" "failed to disable user $USERID"
	done
}

function enableUsers {
	local -r IPMIADMIN=`boxinfo config $CONFIG ipmi ipmiadmin 2> /dev/null`
	local -r IPMIADMINPWD=`boxinfo config $CONFIG ipmi ipmiadminpwd 2> /dev/null`
	local -r IPMIADMINID=2

	if [ "_$IPMIADMIN" == "_1" ]; then
		execlog "ipmitool user set password $IPMIADMINID $IPMIADMINPWD" "" "failed to set password for user admin"
		execlog "ipmitool user enable $IPMIADMINID" "enabling access for user admin" "failed to enable access for user admin"
	fi

	local -i USERID=3
	for SECTIONID in `boxinfo config $CONFIG ipmi_ipmiusers 2> /dev/null`
	do
		local USERNAME=`boxinfo config $CONFIG ipmi_ipmiusers_$SECTIONID ipmiusername 2> /dev/null`
		local PASSWORD=`boxinfo config $CONFIG ipmi_ipmiusers_$SECTIONID ipmipwd 2> /dev/null`
		local LEVEL=`boxinfo config $CONFIG ipmi_ipmiusers_$SECTIONID ipmilevel 2> /dev/null`

		execlog "ipmitool user set name $USERID $USERNAME" "" "failed to set username for user ID $USERID"

		execlog "ipmitool user set password $USERID $PASSWORD" "" "failed to set password for user $USERNAME"
		execlog "ipmitool channel setaccess 1 $USERID link=on ipmi=on callin=on privilege=$LEVEL" "" "failed to set access level for user $USERNAME"

		execlog "ipmitool user enable $USERID" "enabling access for user $USERNAME" "failed to enable access for user $USERNAME"

		USERID=$(( USERID + 1))
	done
}

function disableAccess {
	execlog "ipmitool lan set 1 access off" "disabling remote IPMI access" "failed to disable remote IPMI access"
}

function configureARP {
	local -r IPMIARP=`boxinfo config $CONFIG ipmi ipmiarp 2> /dev/null`
	local -r IPMIGRATARP=`boxinfo config $CONFIG ipmi ipmigratarp 2> /dev/null`
	local -r IPMIGRATARPINTVL=`boxinfo config $CONFIG ipmi ipmigratarpintvl 2> /dev/null`

	if [ "_$IPMIARP" == "_0" ]; then
		execlog "ipmitool lan set 1 arp respond off" "disabling ARP responses" "failed to disable ARP responses"
	else
		execlog "ipmitool lan set 1 arp respond on" "enabling ARP responses" "failed to enable ARP responses"
	fi

	if [ "_$IPMIGRATARP" == "_1" ]; then
		execlog "ipmitool lan set 1 arp interval $IPMIGRATARPINTVL" "setting gratuitous ARP message interval to $IPMIGRATARPINTVL seconds" "failed to set gratuitous ARP message interval"
		execlog "ipmitool lan set 1 arp generate on" "enabling gratuitous ARP messages" "failed to enable gratuitous ARP messages"
	else
		execlog "ipmitool lan set 1 arp generate off" "disabling gratuitous ARP messages" "failed to disable gratuitous ARP messages"
	fi
}

function startTTY {
	i=0
	while [ $i -lt 3 ]; do
		initctl start ttyS1 2>/dev/null &
		sleep 1
		OUT=$(ps auwx|grep initctl|grep -v grep)
		if [ -z "$OUT" ]; then
			break
		fi
		killall -9 initctl
		let i=$i+1
	done
}

function stopTTY {
	i=0
	while [ $i -lt 3 ]; do
		initctl stop ttyS1 2>/dev/null &
		sleep 1
		OUT=$(ps auwx|grep initctl|grep -v grep)
		if [ -z "$OUT" ]; then
			break
		fi
		killall -9 initctl
		let i=$i+1
	done
}

function writeUpstartFile {
	[ -z "$1" ] && return
	cat > /tmp/${1} << EOF
# $1 - getty
# #
# # This service maintains a getty on tty6 from the point the system is
# # started until it is shut down again.

start on stopped rc2
start on stopped rc3
start on stopped rc4
start on stopped rc5

stop on runlevel 0
stop on runlevel 1
stop on runlevel 6

respawn
EOF

	echo $2 >> /tmp/${1}
	mv -f /tmp/${1} /etc/event.d/${1}
}

function configureSOL {
	local -r SOLACTIVE=`boxinfo config $CONFIG ipmi ipmisol 2> /dev/null`

	if [ "_$SOLACTIVE" == "_1" ]; then
		$logerror "Info" "activating Serial-over-LAN"
		writeUpstartFile ttyS1 "exec /sbin/agetty 115200 ttyS1 vt102"

		if [ ! `grep ttyS1 /etc/securetty` ]; then
			/bin/echo ttyS1 >> /etc/securetty
		fi
		if [ "_$BOOT" != "_1" ]; then
			startTTY
		fi
	else
		$logerror "Info" "deactivating Serial-over-LAN"
		set +f
		rm -f /etc/event.d/ttyS1
		set -f
		if [ `grep ttyS1 /etc/securetty` ]; then
			sed -i '/ttyS1/d' /etc/securetty
		fi
		if [ "_$BOOT" != "_1" ]; then
			stopTTY
		fi
	fi
}

# script starts here
MODEL=`boxinfo model 2> /dev/null`
if [[ "_$MODEL" != "_f1000"  && "_$MODEL" != "_f800" && "_$MODEL" != "_f900" ]]; then
	exit 0
fi

# appliances that do not have IPMI
APPLIANCE=`boxinfo appliance 2> /dev/null`
if [[ "_$APPLIANCE" == "_f800" || "_$APPLIANCE" == "_f800b" || "_$APPLIANCE" == "_f900" ]]; then
	exit 0
fi 

IPMIREMOTE=`boxinfo config $CONFIG ipmi ipmiremote 2> /dev/null`

getopts ":b" aopt
case $aopt in
	b)
		BOOT=1
		if [[ "_$IPMIREMOTE" == "_1" || "_$IPMIREMOTE" == "_2" ]]; then
			loadKernelModules
			configureSOL
		fi
		exit 0
	;;
	*)
		BOOT=0
	;;
esac

# everything from here on is activation (i.e. NOT during boot)

if [ ! -e /dev/ipmi0 ]; then
	loadKernelModules
	if [ "$?" != "0" ]; then
		exit 1
	fi
fi

# first, make sure that authentication is secure
setAuth
disableAllUsers

case $IPMIREMOTE in
	1)
		configureDynamicAddress
	;;
	2)
		configureStaticAddress
	;;
	*)
		disableAccess
		stopTTY
		unloadKernelModules
		exit 0
	;;
esac

# this code is only executed if IPMI is active - otherwise the
# "case" above exits
configureARP
configureSOL
enableUsers
