#!/bin/bash

apcc=/etc/apcupsd/apccontrol
apcf=/etc/apcupsd/apcupsd.conf
apcchk=/usr/bp/apc

if [[ -e $apcchk ]]
then
	exit 0
else
	if [[ -e $apcc ]]
	then
		if [[ -e $apcf ]]
		then
			valid="true"
		else
			valid="false"
		fi
	else
		valid="false"
	fi
fi

if [[ $valid = "true" ]]
then
	echo "APCUPSD package has been installed, configuring for automatic USB support"
	touch $apcchk
else
	echo "APCUPSD package has not been installed, Installing APC daemon software"
	pushd /tmp
	wget ftp://updateftp.unitrends.com/utilities/apc/apcupsd-3.14.10-1.el6.rf.x86_64.rpm
	if [[ $? -eq 1 ]]
	then
		echo "There was a problem downloading the required software packages. Please check and make sure that ftp is allowed."
		popd
		exit 1
	fi
	rpm -ivh /tmp/apcupsd-3.14.10-1.el6.rf.x86_64.rpm
	if [[ $? -eq 1 ]]
	then
		echo "Failed to install the downloaded software. Please try again."
		rm -f /tmp/apcupsd-3.14.10-1.el6.rf.x86_64.rpm
		popd
		exit 1
	fi
	touch $apcchk
	popd
fi

sed -i 's/WALL=wall/WALL=wall\nBP_RC=\/etc\/init.d\/bp_rcscript\nlog=\/var\/log\/apcupsd.events/g' $apcc
sed -i 's/echo "UPS ${2} initiating Reboot Sequence" | ${WALL}/echo "UPS ${2} initiating Reboot Sequence" | ${WALL}\n		${BP_RC} stop > $log/g' $apcc
sed -i 's/echo "UPS ${2} initiated Shutdown Sequence" | ${WALL}/echo "UPS ${2} initiated Shutdown Sequence" | ${WALL}\n		${BP_RC} stop > $log/g' $apcc
sed -i 's/UPSCABLE smart/UPSCABLE usb/g' $apcf
sed -i 's/UPSTYPE apcsmart/UPSTYPE usb/g' $apcf
sed -i 's/DEVICE \/dev\/ttyS0/DEVICE/g' $apcf
