#!/bin/bash2


# author: Klaus Gheri, kgheri@barracuda.com
# Copyright Barracuda Networks AG, 2011

# routine used to import addresses from either a flat list, comma or semicolon separated list of IP addresses and CIDR conformant networks.
# for networks a netmask conversion to the internal notation style convention is performed 
# KmgVersionString 5.2.2.3

source /etc/phion/branding

if [[ -f /etc/phion/functions ]]; then
        source /etc/phion/functions
else
	exit 2
fi
ARG0="CustomExternalAddrImport"
ARGS=${@}		# saving the original command line args!


declare -i TOPMAX=500000
declare -i MAXOBJNR=10000

PATH="/sbin:/bin:/usr/sbin:/usr/bin:/opt/phion/bin:/etc/phion/bin"
export PATH="$PATH"

RUNDIR=/var/phion/run/firewall/CustomExternalAddrImport
CONFDIR=/var/phion/preserve/firewall/CustomExternalAddrImport

LOGGER=$(which logger)

[[ ! -d ${RUNDIR} ]] && mkdir -p ${RUNDIR}
[[ ! -d ${CONFDIR} ]] && mkdir -p ${CONFDIR}


OUT=$(phionctrl module show firewall 2>/dev/null)
set -- ${OUT}
SRR=${2}  SRV=${3}

if [[ -f /opt/phion/config/active/servers/${SRR}/services/${SRV}/active.fwrule ]]; then
	MYLOGFLE="srv_${SRR}_${SRV}_CustomExternalImport"
else
	MYLOGFLE="box_Firewall_CustomExternalImport"
	NOHA=1
fi
logerror="LogError $MYLOGFLE"

$logerror "Info" "[0301010] ${ARG0}[$$]: ---------- START ------------------------------"  
CALLER=$(cat /proc/$PPID/cmdline)
$logerror "Info" "[0300100] ${ARG0}[$$]: started up by caller process ${CALLER} with pid ${PPID}"  
 
function fEXIT {
	[[ -f ${IMPORTFLETMP} ]] && rm -f ${IMPORTFLETMP}
	[[ -f ${IMPORTFLETMP}.pruned ]] && rm -f ${IMPORTFLETMP}.pruned
	[[ -f ${CKSUMFLETMP}  ]] && rm -r ${CKSUMFLETMP} 
	[[ -f ${TARGETFLETMP} ]] && rm -f ${TARGETFLETMP}
	$logerror "Info" "[0301010] ${ARG0}[$$]: ----------- END -------------------------------"  
	exit 0
}


trap fEXIT EXIT

 
MAINADMIN=$(/opb/boxinfo mainadmin >/dev/null)

USAGE="Usage: $ARG0 OPTIONS\nOPTIONS:\n -l <1-500000>\t ... maximum number of allowed address entries\n -h\t\t ... do HA sync\n -o <1-4>\t ... mandatory index of network object\n -i /var/phion/home/<admin>/<filename>\t   ... mandatory input data file"
set -- ${ARGS}  		# recreating the original command line args!
while getopts "l:ho:i:" opt; do
	case $opt in
                	
			l)	
				_MAXOBJNR=${MAXOBJNR}
				MAXOBJNR=${OPTARG}
				
				if [[ ${MAXOBJNR:-0} = 0 ]]; then 
					$logerror "Warning" "[0301014] ${ARG0}[$$]: no meaningful new network object limit specified, defaulting to builtin value of ${_MAXOBJNR}"				
				else
					if [[ ${MAXOBJNR} -gt ${TOPMAX} ]]; then
						$logerror "Error" "[0301016] ${ARG0}[$$]: new network object limit exceeds safety threshold of ${TOPMAX}, defaulting to builtin value of ${_MAXOBJNR}"
					else
						$logerror "Notice" "[0301014] ${ARG0}[$$]: overriding builtin default network object limit of ${_MAXOBJNR}, new limit is ${MAXOBJNR} "				
					fi					
				fi
				;;
			
			h)
				$logerror "Notice" "[0301014] ${ARG0}[$$]: enabling HA sync of processed network address information"
				DOHA=1
				[[ ${MAINADMIN:_0} = 1 ]] && {
					$logerror "Notice" "[0301016] ${ARG0}[$$]: HA mode for $BASENAMECC managed unit requested, consider CC based distribution"
				}
				;;
			
			o  )
				$logerror "Notice" "[0301012] ${ARG0}[$$]: setting address target to custom external object ${OPTARG}"
                        	TARGETINDEX=${OPTARG:-1}
				[[ ${TARGETINDEX} -le 0 || ${TARGETINDEX} -gt 4 ]] && {
					$logerror "Error" "[0301030] ${ARG0}[$$]: Illegal target index value"
				}
                        	;;
                	i  ) 
				OUT=${OPTARG#"/var/phion/home/"}
				[[ _"${OPTARG}" = _"${OUT}" ]] && {
					$logerror "Error" "[0301040] ${ARG0}[$$]: input data file path does not point to /var/phion/home"
					exit 1
				}
				OUT=${OUT//../} 				
				[[ _"${OPTARG}" != _"/var/phion/home/${OUT}" ]] && {
					$logerror "Error" "[0301040] ${ARG0}[$$]: input data file path attempts illegal directory traversing"
					exit 1
				}				
				$logerror "Notice" "[0301042] ${ARG0}[$$]: setting full path of input data to ${OPTARG}"
                    		INPUTFLE="${OPTARG}"
                        	;;
                      	\?* ) echo -e "$USAGE"
                     		exit 1
				;;
                	* ) echo -e "$USAGE"
                     		exit 1
				;;
	esac
done


IMPORTDIR=${INPUTFLE%/*}

IMPORTFLE=${INPUTFLE#${IMPORTDIR}\/}
IMPORTFLETMP=${RUNDIR}/${IMPORTFLE}.$$.tmp
#DELIMITER=
TARGETFLE="/opt/phion/config/active/CustomExternal${TARGETINDEX}.conf"
TARGETFLETMP="${RUNDIR}/CustomExternal${TARGETINDEX}.conf.$$.tmp"
CKSUMFLE="${CONFDIR}/CheckSum.${TARGETINDEX}"
CKSUMFLETMP="${RUNDIR}/CheckSum.${TARGETINDEX}.$$.tmp"


#  start out with a check for data and data changes 
function SecurePrune {
	local _ARG1=${1}
	if [[ -f ${_ARG1} ]]; then
		#everything except '.','/',':', ABCDEF, abcdef,0-9, and '\n' (LF)
		#cat ${_ARG1}| tr -d '\000-\011\013-\037\041-\055\073-\100\107-\140\147-\177' > ${_ARG1}.pruned    
		cat ${_ARG1}| tr  '\000-\011\013-\037\041-\055\073-\100\107-\140\147-\177' '\040' > ${_ARG1}.pruned    
		return 0
	else
		return 1
	fi
}



[[ -L ${IMPORTDIR}/${IMPORTFLE} ]] && {
	$logerror "Error" "[0301044] ${ARG0}[$$]: input data file path is a symbolic link, terminating"
	exit 1
}
if [[ -f ${IMPORTDIR}/${IMPORTFLE} ]]; then
	 mv -f ${IMPORTDIR}/${IMPORTFLE} ${IMPORTFLETMP}
else
	$logerror "Notice" "[0300200]  ${ARG0}[$$]: import file ${IMPORTDIR}/${IMPORTFLE} not found, exiting"
	exit 1
fi
# start with check for file and check for changes based on a checksum


# if the file has changed we move it and 
# next we remove the possible demimiters from the file and replace them by blanks (, ; )

# TODO Logging, determine service


ALLADDR=""
CKSUM=$(cksum ${IMPORTFLETMP} 2>/dev/null)	

[[ _"${CKSUM}" != _ ]] && {
	TOTALCT=0
	set -- ${CKSUM}
	CKSUM="$1"
	$logerror "Info" "[0300200]  ${ARG0}[$$]: current import file checksum is ${CKSUM}"
	[[ -f ${CKSUMFLE} ]] && {
		OCKSUM=$(cat ${CKSUMFLE} )
		$logerror "Info" "[0300200]  ${ARG0}[$$]: stored checksum equals ${OCKSUM}"
	}
	if [ _${CKSUM} = _${OCKSUM:-0} ]; then
		$logerror "Info" "[0300200]  ${ARG0}[$$]: import file checksum ${CKSUM} matches stored value, no action needed"
		rm -f ${IMPORTFLETMP}
		exit 1

	else			
		echo ${CKSUM} > ${CKSUMFLETMP}
		if [[ -f ${IMPORTFLETMP} ]]; then
			SecurePrune ${IMPORTFLETMP}   # ${IMPORTFLETMP}.pruned
			#cat ${IMPORTFLETMP}.pruned
			rm -f ${IMPORTFLETMP} &>/dev/null
						
			[[ -f ${IMPORTFLETMP}.pruned ]] && ALLADDR=$(cat ${IMPORTFLETMP}.pruned 2>/dev/null )			
			OUT=""
			let j=0
			for a in ${ALLADDR}; do			
				set -- ${a//\// }
				if [[ ${a} != *[:]* ]]; then
					_MSK=${2}
					if [[ ${2:-__} != __ ]]; then 
						let _MSK=32-_MSK
						a="${1}/${_MSK}"
					fi
				fi
				OUT="${OUT}IP[${j}]=${a}\n"
				let j++
				if [[ ${j} -ge ${MAXOBJNR} ]]; then					
					$logerror "Error" "[0301030]  ${ARG0}[$$]: maximum address list length exceeded, truncating address list at  ${MAXOBJNR} entries"
					$LOGGER -i -puucp.info -tEvent "layer_id=1;layer_name=cron;class_id=1;class_name=${ARG0};type_id=136;type_name=CustomExternalAddressObject${TARGETINDEX};data=maximum address list length exceeded, truncating address list for object ${TARGETINDEX} at  ${MAXOBJNR} entries"	
					break
				else
					:
				fi
			done
			TOTALCT=${j}
			echo -e "${OUT}" > ${TARGETFLETMP}
					
			if [[ -f ${TARGETFLE} ]]; then
				if ! diff --brief ${TARGETFLE} ${TARGETFLETMP} &>/dev/null;  then
					_DOINSERT=1
				fi					
			else
				_DOINSERT=1
			fi
			
			if [[ ${_DOINSERT:-0} = 1 ]]; then			
				# go and determine SRR and SRV names										
				mv -f ${TARGETFLETMP} ${TARGETFLE}
				$logerror "Notice" "[0301020]  ${ARG0}[$$]: writing new custom external address object ${TARGETINDEX} containing ${TOTALCT} entries"
				[[ -f /opt/phion/config/active/servers/${SRR}/services/${SRV}/active.fwrule ]] && touch /opt/phion/config/active/servers/${SRR}/services/${SRV}/active.fwrule
				acpfrule i &>/dev/null
				
				[[ -f  ${CKSUMFLETMP} ]] && {
					mv -f ${CKSUMFLETMP} ${CKSUMFLE}
					$logerror "Info" "[0300200]  ${ARG0}[$$]: created new stored checksum ${CKSUM}"
				}				
				# TODO log event
				
				
				[[ ${NOHA:-0} != 1 ]] && { 
					[[ ${DOHA:-0} = 1 ]] && {
					 	# need server name only!!
						/opt/phion/modules/box/boxsrv/dist/bin/dist2client -P -r ${SRR} -f ${TARGETFLE} -p put

					   	if [[ $? != 0 ]]; then
							   $logerror "Error" "[0301060]  ${ARG0}[$$]: HA synchronization failed"
							   # EVENT?
						else
							   $logerror "Notice" "[0301062]  ${ARG0}[$$]: HA synchronization successful"
							   /opt/phion/modules/box/boxsrv/dist/bin/dist2client -P -r ${SRR} -f /opb/acpfrule -a 'i' -p exec  #TODO	
						fi
				   	}
				}
			else
				$logerror "Info" "[0300200]  ${ARG0}[$$]: no data changes detected, no need for action"
			fi																		
		else
			$logerror "Error" "[0300200]  ${ARG0}[$$]: missing working copy of import file ${IMPORTFLETMP}"
			exit 1
		fi
	fi	
	exit 0
}
$logerror "Error" "[0300200]  ${ARG0}[$$]: missing checksum value for working copy of import file."
exit 1	
