#!/bin/bash

#The localdomains domain removal script, to remove domains that are requested 
#by customers to be delivered remote to the cPanel server, and add them to remotedomains
#Any questions should be directed to Andrew Kay (andrew.kay@zeninternet.co.uk)

#Some commonly used files
local=/etc/localdomains
localout=/home/cpstatus/localdomains.temp
remote=/etc/remotedomains
localbackup=/etc/localdomains.auto.backup

#So the verification of the below test doesn't throw up an error
/bin/touch $localout

#Local and Remotedomain file tests to make sure the domain exists in either file
testlocal=`/bin/cat $local | /bin/egrep -c ^$1$`
testlocalout=`/bin/cat $localout | /bin/egrep -c ^$1$`
testremot=`/bin/cat $remote | /bin/egrep -c ^$1$`

#Line number checking to make sure the full file has been written back to the temporary file
wctestlocal=`egrep -c "" $local`
wctestremot=`egrep -c "" $remote`

#Start of operations to remove domain from localdomains and add it to remotedomains
if [ $testlocal -gt "0" ]
	then
	#Take a backup of localdomains
	cp $local $localbackup
		#Make sure there isn't more than 1 match to the query, or it could get messy
		if [ $testlocal -gt "1" ]
			then
			/bin/echo "Too many matches found"
			else
			#Remove the domain from local domains
			/bin/cat $local | /bin/egrep -v $1 > $localout
			/bin/echo "Domain removed from /etc/localdomains"
		fi
		if [ $testlocalout -gt "0" ]
			then
			/bin/echo "Domain name not removed"
			else
			#Test to make sure the new file isn't too small, and that only 1 line has been removed
			#This mainly tests to make sure the file isn't too small
			wctestoutput=`egrep -c "" $localout`
			wctest=$(($wctestoutput +1))
			if [ $wctest == $wctestlocal ]
				then
				/bin/echo "All is good, copying the new file over to take place of the original"
				mv -f $localout $local
				#Test that the domain name isn't already an entry in the remotedomains file
	                	if [ $testremot -gt "1" ]
	                		then
	                		/bin/echo "Not added to remote domains, already present"
	                		else
	                		#Add the domain name to remotedomains
	                		/bin/echo $1 >> $remote
	                		/bin/echo "Domain added to $remote, if anything goes wrong, there's a backup ($localbackup)"
	                	fi
			else
			/bin/echo "Something went wrong, remove the domain manually"
			fi
		fi
	else
	/bin/echo "No domains found in `echo $local`"
fi
