#!/bin/bash

EPP_INSTALL_LOG="/tmp/epp-install.log"
EPP_INSTALL_CONFIG="/tmp/epp-srv201f0dd30"

echo "Post-flight ----- " `date` "id: " `id -u -nr` >> ${EPP_INSTALL_LOG}

#check if this is an upgrade and stop the daemon, and kext
val=`ps axc | grep -c EppClient`
if [ $val -ge "1" ]; then
	echo "Stopping the old Endpoint Protector daemon ..."  >> ${EPP_INSTALL_LOG}
	/sbin/SystemStarter stop "Endpoint Protector" >> ${EPP_INSTALL_LOG}
else
	echo "The Endpoint Protector daemon is not running." >> ${EPP_INSTALL_LOG}
fi

val=`kextstat | grep -c EPPDeviceController`
if [ $val -eq "1" ]; then
	echo "The old kernel extension is loaded ... stopping." >> ${EPP_INSTALL_LOG}
    kextunload /System/Library/Extensions/EPPDeviceController.kext	
else
	echo "The kernel extension is not loaded." >> ${EPP_INSTALL_LOG}
fi

# !end update check

#copy the server settings to the configuration file
cat ${EPP_INSTALL_CONFIG} >> /private/etc/epp/options.ini

val=`grep -c "ws_server" /private/etc/epp/options.ini 2> /dev/null`
if [ $val -ge "1" ]; then
	echo "Server: " `grep "ws_server" /private/etc/epp/options.ini` >> ${EPP_INSTALL_LOG}
else
	echo "NO server address configured" >> ${EPP_INSTALL_LOG}
	exit 1
fi

# check if this Mac is Snow Leopard or newer 
# (then we can use the 10.6 SDK, and support 64 bit arch)
val=`sw_vers -productVersion`
if [ "$val" '<' "10.6" ]; then
    echo "OS Product Version is: $val , Tiger or Leopard"  >> ${EPP_INSTALL_LOG}
    if [ -d "/private/etc/EPPDeviceController.kext" ]; then
    	rm -rf /private/etc/EPPDeviceController.kext
    fi
else
	echo "OS Product Version is: $val , Snow Leopard or newer"  >> ${EPP_INSTALL_LOG}

	if [ -d "/System/Library/Extensions/EPPDeviceController.kext" ]; then
		rm -rf /System/Library/Extensions/EPPDeviceController.kext
	fi

	cp -R /private/etc/epp/EPPDeviceController.kext /System/Library/Extensions/
	chown -R root:wheel /System/Library/Extensions/EPPDeviceController.kext
	chmod -R 755 /System/Library/Extensions/EPPDeviceController.kext
	rm -rf /private/etc/EPPDeviceController.kext
fi

# at this point the server configuration should be OK, start EPP kext and daemon
val=`kextstat | grep -c EPPDeviceController`
if [ $val -eq "1" ]; then
	echo "kext is loaded"  >> ${EPP_INSTALL_LOG}
else
	echo "Loading kext ..." >> ${EPP_INSTALL_LOG}
	kextload "/System/Library/Extensions/EPPDeviceController.kext"
fi

val=`ps axc | grep -c EppClient`
if [ $val -ge "1" ]; then
	echo "daemon already running" >> ${EPP_INSTALL_LOG}
else
	echo "Starting daemon ..." >> ${EPP_INSTALL_LOG}
	/sbin/SystemStarter start "Endpoint Protector"	
fi

if [ $? -eq "0" ]; then
    echo "EPP installation successful" >> ${EPP_INSTALL_LOG}
    rm ${EPP_INSTALL_LOG}
    rm ${EPP_INSTALL_CONFIG}
else    
	echo "EPP installation FAILED!" >> ${EPP_INSTALL_LOG}
fi
