#!/bin/bash

usage="
Usage: $(basename $0) ROUTING-IP [OLD-ROUTING-IP]

Setup connection objects needed for Azure vWAN operation.

The tool expects a ROUTING-IP of the next-hop routing VPN interface as a parameter.

If a second parameter, OLD-ROUTING-IP, is given, 
then the corresponding connection object is deleted.
"

tmpfile=

function error_exit() {
    local message=$1
    local print_usage=$2
    >&2 echo "$message; aborting."
    if [[ -n "$print_usage" ]]; then
	echo "$usage"
    fi
    if [[ -n "$tmpfile" ]]; then
	rm -f "$tmpfile"
    fi
    exit 1
}

DELETECMD=

if [[ "$1" == "--help" ]]; then
    echo "$usage"
    exit 0
fi

if [[ $# -lt 1 || $# -gt 2 ]]; then
    error_exit "wrong number of arguments" usage
fi

if [[ $# -eq 2 && "$2" != "$1" ]]; then
    DELETECMD="--delete connection VWAN-nhra$2"
fi

# create temporary file
tmpfile=$(mktemp -q --tmpdir="./")
if [[ $? -ne 0 || ! -f "$tmpfile" ]]; then
    error_exit "failed to create a temporary file"
fi

# dynamic parameters to substitute into the firewall rules
VWANROUTINGIP=$1

# output firewall rules to be merged into a temporary file;
# substitute dynamic parameters
(
cat << END-OF-FW-RULES

RuleSet{
	name={}
	readOnly={0}
	origin={}
	global={0}
	comment={}
	objrenamed={0}
	baseid={0}
	incid={1}
	featureLevel={16}
	useAppRules={0}
	id={}
	transobj={7.1.1.1}
	creator={}
	localCascade={0}
	allowRID={0}
	allowAppRules={0}
	prefixmatch={
	}
	rulesettype={}
	loadsets={}
	name={}
	readOnly={0}
	origin={}
	global={0}
	comment={}
	netprefixobj={
	}
	netprefixobj6={
	}
	netobj={
		NetESet{
			name={Trusted LAN Networks}
			readOnly={1}
			origin={}
			global={0}
			comment={All trusted local area networks}
			extlist={
				ExtDef{
					name={ManagementNetwork}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					sourceType={boxconf}
					sourceFile={boxnet.conf}
					sectionPattern={boxnet}
					addrKey={ip}
					maskKey={mask}
					encoding={maskint}
					conditions={realm=1}
				}
				ExtDef{
					name={LocalNetworks}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					sourceType={boxconf}
					sourceFile={boxnet.conf}
					sectionPattern={addnet_*}
					addrKey={ip}
					maskKey={mask}
					encoding={maskint}
					conditions={realm=1}
				}
				ExtDef{
					name={Routes}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					sourceType={boxconf}
					sourceFile={boxnet.conf}
					sectionPattern={addroute_*}
					addrKey={target}
					maskKey={}
					encoding={addr}
					conditions={realm=1|type=dev}
				}
				ExtDef{
					name={LowLevelTunnels}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					sourceType={boxconf}
					sourceFile={boxnet.conf}
					sectionPattern={tunnel_*}
					addrKey={target}
					maskKey={}
					encoding={addr}
					conditions={realm=1}
				}
			}
		}
		NetESet{
			name={Trusted Next-Hop Networks}
			readOnly={1}
			origin={}
			global={0}
			comment={All trusted networks reachable through a next-hop}
			extlist={
				ExtDef{
					name={NextHopRoutes}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					sourceType={boxconf}
					sourceFile={boxnet.conf}
					sectionPattern={addroute_*}
					addrKey={target}
					maskKey={}
					encoding={addr}
					conditions={realm=1|type=*gw}
				}
			}
		}
		NetSet{
			name={Trusted LAN}
			readOnly={0}
			origin={}
			global={0}
			comment={All network addresses that have a trusted classification. This automatically applies to the management network.}
			list={
				NetRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={All trusted local area networks}
					ref={Trusted LAN Networks}
				}
				NetRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={All trusted networks reachable through a next-hop}
					ref={Trusted Next-Hop Networks}
				}
			}
			neglist={
			}
		}
		NetSet{
			name={Any}
			readOnly={0}
			origin={}
			global={0}
			comment={All IPv4 addresses}
			list={
				NetEntry{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					addr={0.0.0.0/32}
				}
			}
			neglist={
			}
		}
		NetSet{
			name={Internet}
			readOnly={0}
			origin={}
			global={0}
			comment={All routed IPv4 addresses}
			list={
				NetRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Any}
				}
			}
			neglist={
				NetEntry{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					addr={10.0.0.0/24}
				}
				NetEntry{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					addr={172.16.0.0/20}
				}
				NetEntry{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					addr={192.168.0.0/16}
				}
			}
		}
	}
	srvobj={
		ServiceSet{
			name={FTP}
			readOnly={0}
			origin={}
			global={0}
			comment={FTP using plugin module}
			list={
				ServiceEntryTCP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ 21}
					sessionTimeout={86400}
					balancedTimeout={20}
					writeTimeout={60}
					botClientPort={1024}
					topClientPort={65535}
					ownProc={0}
					pluginModule={ftp}
					srvText={ftp}
					detectPolicy={1}
					listingPolicy={0}
					detectAllowBits2={16777216,0,0,0,0,0}
				}

			}
		}
		ServiceSet{
			name={FTPS}
			readOnly={0}
			origin={}
			global={0}
			comment={Implicit FTPS using FTP firewall plugin. SSL Interception required.}
			list={
				ServiceEntryTCP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ 990}
					sessionTimeout={86400}
					balancedTimeout={20}
					writeTimeout={60}
					botClientPort={1024}
					topClientPort={65535}
					ownProc={0}
					pluginModule={ftp}
					srvText={ftp}
					detectAllowBits2={16777216,0,0,0,0,0}
				}

			}
		}
		ServiceSet{
			name={RCMD}
			readOnly={0}
			origin={}
			global={0}
			comment={Remote shell, remote exec, and remote login services}
			list={
				ServiceEntryTCP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ 514}
					sessionTimeout={86400}
					balancedTimeout={20}
					writeTimeout={60}
					botClientPort={512}
					topClientPort={1023}
					ownProc={0}
					pluginModule={rsh}
					srvText={rsh}
				}

				ServiceEntryTCP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ 512}
					sessionTimeout={86400}
					balancedTimeout={20}
					writeTimeout={60}
					botClientPort={512}
					topClientPort={1023}
					ownProc={0}
					pluginModule={}
					srvText={rexec}
				}

				ServiceEntryTCP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ 513}
					sessionTimeout={86400}
					balancedTimeout={0}
					writeTimeout={60}
					botClientPort={1024}
					topClientPort={65535}
					ownProc={0}
					pluginModule={}
					srvText={rlogin}
				}

			}
		}
		ServiceSet{
			name={Any-TCP}
			readOnly={0}
			origin={}
			global={0}
			comment={All TCP ports}
			list={
				ServiceRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={FTP connection with plugin module}
					ref={FTP}
				}

				ServiceRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={FTPS connection with plugin module}
					ref={FTPS}
				}

				ServiceRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={RCMD}
				}

				ServiceEntryTCP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ *}
					sessionTimeout={86400}
					balancedTimeout={20}
					writeTimeout={60}
					botClientPort={1024}
					topClientPort={65535}
					ownProc={0}
					pluginModule={}
				}

			}
		}
		ServiceSet{
			name={Any-UDP}
			readOnly={0}
			origin={}
			global={0}
			comment={All UDP ports}
			list={
				ServiceEntryUDP{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={ *}
					sessionTimeout={60}
					balancedTimeout={20}
					writeTimeout={60}
					botClientPort={2048}
					topClientPort={65535}
					ownProc={0}
					pluginModule={}
					 udpReversedAny={0}
				}

			}
		}
		ServiceSet{
			name={ICMP}
			readOnly={0}
			origin={}
			global={0}
			comment={ICMP-ECHO service limited to 10000 bytes and 10ms interval}
			list={
				ServiceEntryEcho{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					sessionTimeout={20}
					balancedTimeout={10}
					 minDelay={10}
					 maxSize={10000}
				}

			}
		}
		ServiceSet{
			name={Any}
			readOnly={0}
			origin={}
			global={0}
			comment={All TCP, UDP, and ICMP services and other IP protocols}
			list={
				ServiceRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Any-TCP}
				}

				ServiceRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Any-UDP}
				}

				ServiceRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={ICMP}
				}

				ServiceEntryOther{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					portLimit={}
					sessionTimeout={120}
					balancedTimeout={120}
					writeTimeout={60}
					botClientPort={1024}
					topClientPort={65535}
					ownProc={0}
					pluginModule={}
					 proto={0}
				}

			}
		}
	}
	appobj={
	}
	contentobj={
	}
	protoobj={
	}
	filterobj={
	}
	filtergroupobj={
	}
	parpobj={
	}
	devgroupobj={
		DevGroup{
			name={Matching}
			readOnly={0}
			origin={}
			global={0}
			comment={Select this object to make use of IP spoofing protection.}
			list={match}
		}
	}
	icmpparamobj={
	}
	connobj={
		ConnStd{
			name={Dynamic NAT}
			readOnly={0}
			origin={}
			global={0}
			comment={Source NAT using local IP address obtained from a routing lookup to the destination}
			connTimeout={30}
			connIPType={PROXY_DYNAMIC}
			connIP={0.0.0.0}
			device={}
			connMask={0}
			samePort={0}
			cycleType={0}
			cyclePrimWeight={1}
		}
		ConnStd{
			name={VWAN-nhra$VWANROUTINGIP}
			readOnly={0}
			origin={}
			global={0}
			comment={}
			connTimeout={30}
			connIPType={CLIENT}
			connIP={0.0.0.0}
			device={}
			connMask={0}
			samePort={1}
			cycleType={0}
			cyclePrimWeight={1}
		}
		ConnStd{
			name={VWAN-DefaultBreakout}
			readOnly={0}
			origin={}
			global={0}
			comment={}
			dynType={ConnApp}
			connTimeout={30}
			connIPType={PROXY_DYNAMIC}
			connIP={0.0.0.0}
			device={}
			connMask={0}
			samePort={0}
			cycleType={0}
			cyclePrimWeight={1}
			connapplist={
				ConnAppEntry{
					name={Azure-vwantun}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					appCatFilter={2048}
					conn={
						ConnRef{
							name={}
							readOnly={0}
							origin={}
							global={0}
							comment={}
							ref={VWAN-nhra$VWANROUTINGIP}
						}
					}
				}
			}
			defaultConn={
				ConnRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Dynamic NAT}
				}
			}
		}
		ConnStd{
			name={VWAN-DefaultTunnel}
			readOnly={0}
			origin={}
			global={0}
			comment={}
			dynType={ConnApp}
			connTimeout={30}
			connIPType={CLIENT}
			connIP={0.0.0.0}
			device={}
			connMask={0}
			samePort={1}
			cycleType={0}
			cyclePrimWeight={1}
			connapplist={
				ConnAppEntry{
					name={Azure-vwandirect}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					appCatFilter={2048}
					conn={
						ConnRef{
							name={}
							readOnly={0}
							origin={}
							global={0}
							comment={}
							ref={Dynamic NAT}
						}
					}
				}
			}
			defaultConn={
				ConnRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={VWAN-nhra$VWANROUTINGIP}
				}
			}
		}
	}
	rules={
		Rule{
			name={LAN-2-INTERNET}
			readOnly={0}
			origin={}
			global={0}
			comment={Allows Internet access from trusted LAN for typical applications}
			srcExplicit={
				NetSet{
					name={LAN-2-INTERNET:src}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					list={
						NetRef{
							name={}
							readOnly={0}
							origin={}
							global={0}
							comment={}
							ref={Trusted LAN}
						}
					}
					neglist={
					}
				}
			}
			dstExplicit={
				NetSet{
					name={LAN-2-INTERNET:dst}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					list={
						NetRef{
							name={}
							readOnly={0}
							origin={}
							global={0}
							comment={}
							ref={Internet}
						}
					}
					neglist={
					}
				}
			}
			srv={
				ServiceRef{
					name={LAN-2-INTERNET:srv}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Any}
				}
			}
			action={
				ActionPass{
					name={LAN-2-INTERNET:action}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					eventLevel={-1}
					conn={
						ConnRef{
							name={LAN-2-INTERNET:action:conn}
							readOnly={0}
							origin={}
							global={0}
							comment={}
							ref={VWAN-DefaultTunnel}
						}
					}
					bothWays={0}
				}
			}
			parp={
				PARPRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={}
				}
			}
			filtergroup={
				FilterGroupRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={}
				}
			}
			devgroup={
				DevGroupRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Matching}
				}
			}
			revdevgroup={
				DevGroupRef{
					name={}
					readOnly={0}
					origin={}
					global={0}
					comment={}
					ref={Matching}
				}
			}
			aclService={}
			devBlock={1}
			srcBlock={0}
			dstBlock={0}
			srvBlock={0}
			userBlock={0}
			macBlock={0}
			deactivated={0}
			timeAllow={0,0,0,0,0,0,0,0}
			dynamic={0}
			usesocket={0}
			protipPolicy={0}
			clearDF={0}
			noSync={0}
			noACache={0}
			noLog={0}
			noStat={0}
			logState={0}
			lastackTimeout={10}
			acceptTimeout={10}
			retransTimeout={300}
			durationTimeout={0}
			halfsideTimeout={30}
			noNagle={0}
			ownLog={0}
			logPolicy={0}
			ridType={0}
			rid={-1}
			resolveSrv={0}
			priority={2}
			ignoreGlobalMaxInst={0}
			maxInst={0}
			maxInstSrc={0}
			acceptPolicy={1}
			reversePolicy={1}
			matchIF={0}
		}
	}
	testobj={
	}
	subsets={
	}
	sublists={
	}
}

END-OF-FW-RULES
) > $tmpfile

# call rulemerge with the appropriate parameters

/opt/phion/bin/rulemerge $tmpfile --featurelevel 16 --keep all --replace connection "VWAN-DefaultBreakout" "VWAN-DefaultTunnel" $DELETECMD
exitcode=$?

# clean up
rm -rf $tmpfile

exit $exitcode
