#!/bin/sh
. /lib/functions.sh

configavailable=0
configrespond=0

IPSEC_VAR_PATH=/var/ipsec
IPSEC_PATH=/etc/ipsec.d
IPSEC_PATH_CONFIG=/etc/ipsec.conf
IPSEC_PATH_SECRET=/etc/ipsec.secrets
IPSEC_VAR_CONFIG_FILE="$IPSEC_VAR_PATH/*.conf"
IPSEC_VAR_SECRET_FILE="$IPSEC_VAR_PATH/*.secrets"
SCEP_CERT_PATH=/etc/scep

handle_delete_ipt_nat_rule() {
	local configname="$1"
	local CONFIG="$IPSEC_VAR_PATH/$configname"

	/usr/bin/logger -t IPSEC_uptime -p info "Delete NAT rule: $configname"
	config_load ipsec
	config_get nat_enable "$configname" natenable
	config_get left_subnet "$configname" leftsubnet
	config_get right_subnet "$configname" rightsubnet

	left_subnet=$(echo $left_subnet | sed -e "s/ /,/g" | xargs echo -n)
	right_subnet=$(echo $right_subnet | sed -e "s/ /,/g" | xargs echo -n)

	#Delete postrouting rule if it is present
	iptables -w -t nat -L 'srcnat_ipsec' > /dev/null 2>&1
	if [ "$?" == "0" ]; then
		ipt_rule_handle=$(iptables -w -t nat --line-numbers -nvL 'srcnat_ipsec' | grep "postrouting_$configname" | awk -F '' '{print$1}' | xargs echo -n)
		if [ "$ipt_rule_handle" != "" ]; then
			iptables -w -t nat -D 'srcnat_ipsec' "$ipt_rule_handle" > /dev/null 2>&1
			sleep 2
		fi
	fi

	#Delete prerouting rule if it is present
	iptables -w -t nat -L 'dstnat_ipsec' > /dev/null 2>&1
	if [ "$?" == "0" ]; then
		ipt_rule_handle=$(iptables -w -t nat --line-numbers -nvL 'dstnat_ipsec' | grep "prerouting_$configname" |  awk -F '' '{print$1}' | xargs echo -n)
		if [ "$ipt_rule_handle" != "" ]; then
			iptables -w -t nat -D 'dstnat_ipsec' "$ipt_rule_handle" > /dev/null 2>&1
			sleep 2
		fi
	fi

	#check if static route is present and delete
	lan_ip=`ifstatus lan | jsonfilter -e '@["ipv4-address"][0].address'`
	checkip=`ip route | grep "$right_subnet via $lan_ip dev br-lan proto static" | wc -l`
	if [ $checkip -gt 0 ]; then
		sleep 2
		ip route del $right_subnet via $lan_ip dev br-lan proto static > /dev/null 2>&1
		sleep 3
		rm -rf "$CONFIG/staticroute"
	fi

	while true; do
		# Check whether chain existed or not
		iptables -w -t nat -L 'srcnat_ipsec' > /dev/null 2>&1
		if [ "$?" == "0" ]; then
			ipt_rule_handle=$(iptables -w -t nat --line-numbers -nvL 'srcnat_ipsec' | grep "postrouting_$configname" | grep -m 1 "out pol ipsec" | awk -F ' ' '{print$1}' | xargs echo -n)
			if [ "$ipt_rule_handle" != "" ]; then
				#Delete rule
				iptables -w -t nat -D 'srcnat_ipsec' "$ipt_rule_handle"
			else
				break
			fi
		fi
	done
}

handle_ipt_add_respond_rule() {
	/usr/bin/logger -t IPSEC -p info "Adding iptables rule"
	configrespond=0
	config_load ipsec
	config_foreach check_config_available ipsec
	if [ $configrespond -eq 1 ]; then
		#Add ipt rule to accept port 500 and 4500 to respond
		iptables -w -C INPUT -p udp --dport  500 -j ACCEPT > /dev/null 2>&1
		if [ "$?" != "0" ]; then
			iptables -w -I INPUT -p udp --dport  500 -j ACCEPT > /dev/null 2>&1
			sleep 1
		fi

		iptables -w -C INPUT -p udp --dport  4500 -j ACCEPT > /dev/null 2>&1
		if [ "$?" != "0" ]; then
			iptables -w -I INPUT -p udp --dport  4500 -j ACCEPT > /dev/null 2>&1
			sleep 1
		fi
	fi
}

handle_ipt_delete_respond_rule() {
	configrespond=0
	config_load ipsec
	config_foreach check_config_available ipsec

	if [ $configrespond -eq 0 ]; then
		#delete ipt rule for port 500 and 4500
		while true; do
			iptables -w -C INPUT -p udp --dport  500 -j ACCEPT > /dev/null 2>&1
			if [ "$?" == "0" ]; then
				iptables -w -D INPUT -p udp --dport  500 -j ACCEPT > /dev/null 2>&1
				sleep 1
			else
				break
			fi
		done

		while true; do
			iptables -w -C INPUT -p udp --dport  4500 -j ACCEPT > /dev/null 2>&1
			if [ "$?" == "0" ]; then
				iptables -w -D INPUT -p udp --dport  4500 -j ACCEPT > /dev/null 2>&1
				sleep 1
			else
				break
			fi
		done
	fi
}

handle_ipt_start_service() {
	#Add iptables ipsec prerouting chain
	iptables -w -t nat -L 'srcnat_ipsec' > /dev/null 2>&1
	if [ "$?" != "0" ]; then
		iptables -w -t nat -N 'srcnat_ipsec' > /dev/null 2>&1
		sleep 1
	fi

	#Add iptables ipsec postrouting chain
	iptables -w -t nat -L 'dstnat_ipsec' > /dev/null 2>&1
	if [ "$?" != "0" ]; then
		iptables -w -t nat -N 'dstnat_ipsec' > /dev/null 2>&1
		sleep 1
	fi

	#Add iptables ipsec prerouting jump rule
	iptables -w -t nat -C PREROUTING -j 'dstnat_ipsec' > /dev/null 2>&1
	if [ "$?" != "0" ]; then
		iptables -w -t nat -I PREROUTING -j 'dstnat_ipsec' > /dev/null 2>&1
		sleep 1
	fi

	#Add iptables ipsec postrouting jump rule
	iptables -w -t nat -C POSTROUTING -j 'srcnat_ipsec' > /dev/null 2>&1
	if [ "$?" != "0" ]; then
		iptables -w -t nat -I POSTROUTING -j 'srcnat_ipsec' > /dev/null 2>&1
		sleep 1
	fi
}

handle_ipt_stop_service() {
	/usr/bin/logger -t IPSEC -p info "ipsec stop handle ipt"
	#Delete iptables ipsec prerouting jump rule
	while true; do
		iptables -w -t nat -C PREROUTING -j 'dstnat_ipsec' > /dev/null 2>&1
		if [ "$?" == "0" ]; then
			iptables -w -t nat -D PREROUTING -j 'dstnat_ipsec' > /dev/null 2>&1
			sleep 1
		else
			break
		fi
	done

	#Add iptables ipsec postrouting jump rule
	while true; do
		iptables -w -t nat -C POSTROUTING -j 'srcnat_ipsec' > /dev/null 2>&1
		if [ "$?" == "0" ]; then
			iptables -w -t nat -D POSTROUTING -j 'srcnat_ipsec' > /dev/null 2>&1
			sleep 1
		else
			break
		fi
	done

	while true; do
		iptables -w -t nat -L 'srcnat_ipsec' > /dev/null 2>&1
		if [ "$?" == "0" ]; then
			iptables -w -t nat -F 'srcnat_ipsec' > /dev/null 2>&1
			iptables -w -t nat -X 'srcnat_ipsec' > /dev/null 2>&1
			sleep 1
		else
			break
		fi
	done

	while true; do
		iptables -w -t nat -L 'dstnat_ipsec' > /dev/null 2>&1
		if [ "$?" == "0" ]; then
			iptables -w -t nat -F 'dstnat_ipsec' > /dev/null 2>&1
			iptables -w -t nat -X 'dstnat_ipsec' > /dev/null 2>&1
			sleep 1
		else
			break
		fi
	done
	/usr/bin/logger -t IPSEC -p info "ipsec stop handle ipt end"
}

check_config_available() {
	local configname="$1"
	config_get enable $configname enable
	config_get conntype $configname conntype
	if [ "$enable" == "1" ]; then
		configavailable=1
		if [ "$conntype" == "respond" ]; then
			configrespond=1
		fi
	fi
}

update_ipsec_config() {
	local configname="$1"
	/usr/bin/logger -t IPSEC -p info  "update ipsec config: $configname"

	config_get conn "$configname" conn
	config_get proto "$configname" proto
	config_get ex "$configname" ex
	config_get serverip "$configname" serverip
	config_get method "$configname" method
	config_get left_subnet "$configname" leftsubnet
	config_get right_subnet "$configname" rightsubnet
	config_get keymode "$configname" keymode
	config_get key "$configname" key
	config_get left_id "$configname" leftid
	config_get left_id_sub "$configname" leftid_sub
	config_get right_id "$configname" rightid
	config_get password "$configname" password
	config_get interface "$configname" interface
	config_get ikeencrypt1 "$configname" ikeencrypt1
	config_get ikeencrypt2 "$configname" ikeencrypt2
	config_get ikehash "$configname" ikehash
	config_get espencrypt "$configname" ipsecencrypt
	config_get esphash "$configname" ipsechash
	config_get dhgroup1 "$configname" dhgroup1
	config_get dhgroup2 "$configname" dhgroup2
	config_get dpddelay "$configname" dpdkeep
	config_get dpdtimeout "$configname" dpdtime
	config_get dpdaction "$configname" dpdaction
	config_get certname "$configname" certname
	config_get scepclient "$configname" scepclient
	config_get scepcerttype "$configname" scepcerttype
	config_get scepcertkey "$configname" scepcertkey
	config_get certkey "$configname" certkey
	config_get strictcipher "$configname" strictcipher
	config_get ikemod "$configname" ikemod
	config_get salife "$configname" salife
	config_get ikereykey "$configname" ikereykey
	config_get natenable "$configname" natenable
	config_get nat_subnet "$configname" natsubnet
	config_get force_encaps "$configname" forceencaps
	config_get tunneltype "$configname" tunneltype

	#serverip=$(echo -n `resolveip -4 $serverip`)
	left=""

	if [[ "$dpdaction" != "none" && "$dpdaction" != "hold" ]]; then
		dpdaction="clear"
	fi

	if [ "$serverip" == "" ]; then
		serverip=%any
	fi

	if [ "$right_subnet" == "" ]; then
		right_subnet=%any
	fi

	if [ "$left_subnet" == "" ]; then
		left_subnet=%any
	fi

	if [ "$ex" == "ikev1" ]; then
		ikeencrypt="$ikeencrypt1"
	elif [ "$ex" == "ikev2" ]; then
		ikeencrypt="$ikeencrypt2"
	fi 

	mkdir -p "$IPSEC_VAR_PATH"
	mkdir -p "$IPSEC_VAR_PATH/$configname"
	
	touch "$IPSEC_PATH_CONFIG"
	touch "$IPSEC_PATH_SECRET"

	echo "include $IPSEC_VAR_CONFIG_FILE" > "$IPSEC_PATH_CONFIG"
	echo "include $IPSEC_VAR_SECRET_FILE" > "$IPSEC_PATH_SECRET"

	conf="$IPSEC_VAR_PATH/$configname.conf"
	secret="$IPSEC_VAR_PATH/$configname.secrets"

	#Remove old config if exist
	[ -e "$conf" ]  && rm -rf "$conf"
	[ -e "$secret" ] && rm -rf "$secret"

	#Create a file
	touch "$conf"
	touch "$secret"

	if [ "$proto" == "gateway_to_gateway" ]; then
		echo -e "\nconn $conn" >> "$conf"
		echo -e "\tkeyexchange=$ex" >> "$conf"
		echo -e "\tleft=$left" >> "$conf"

		if [ "$natenable" == "1" ]; then
			left_subnet=$(echo $nat_subnet | xargs echo -n)
		else
			left_subnet=$(echo $left_subnet | sed -e "s/ /,/g" | xargs echo -n)
		fi
		echo -e "\tleftsubnet=$left_subnet" >> "$conf"
		echo -e "\tright=$serverip" >> "$conf"

		right_subnet=$(echo $right_subnet | sed -e "s/ /,/g" | xargs echo -n)
		echo -e "\trightsubnet=$right_subnet" >> "$conf"
		echo -e "\tauto=add" >> "$conf"
		echo -e "\ttype=$tunneltype" >> "$conf"
		echo -e "\tdpdaction=$dpdaction" >> "$conf"
		echo -e "\tlifetime=$salife" >> "$conf"
		echo -e "\tikelifetime=$ikereykey" >> "$conf"

		ike=""
		esp=""

		if [ "$ikeencrypt" != "any" ]; then
			ike=$ikehash-$ikeencrypt-$dhgroup1
		fi
		if [ "$espencrypt" != "any" ]; then
			if [ "$dhgroup2" != "any" ]; then
				if [ "$esphash" == "" ]; then
					esp=$espencrypt-$dhgroup2
				else
					esp=$esphash-$espencrypt-$dhgroup2
				fi
			else
				if [ "$esphash" == "" ]; then
					esp=$espencrypt
				else
					esp=$esphash-$espencrypt
				fi
			fi
		fi
		#Check if it is strict cipher
		if [[ "$strictcipher" == "" || "$strictcipher" == "0" ]]; then
			if [ "$ike" != "" ]; then
				echo -e "\tike=$ike" >> "$conf"
			fi
			if [ "$esp" != "" ]; then
				echo -e "\tesp=$esp" >> "$conf"
			fi
		elif [ "$strictcipher" == "1" ]; then
			if [ "$ike" != "" ]; then
				echo -e "\tike=$ike!" >> "$conf"
			fi
			if [ "$esp" != "" ]; then
				echo -e "\tesp=$esp!" >> "$conf"
			fi
		fi
		if [ "$ikemod" == "aggressive" ]; then
			echo -e "\taggressive=yes" >> "$conf"
		fi

		if [ "$keymode" == "psk" ]; then
			echo -e "\tauthby=secret" >> "$conf"

			#Loading secrets
			if [ "$left_id" != "" ]; then
				echo -e "\tleftid=$left_id" >> "$conf"
			fi
			if [ "$right_id" != "" ]; then
				echo -e "\trightid=$right_id" >> "$conf"
			fi
			echo -e "$left_id $right_id : PSK \"$key\"" > "$secret"
		elif [ "$keymode" == "rsasig" ]; then
			left_cert=$(uci get ipsec.$configname.cert)
			left_key=$(uci get ipsec.$configname.ckey)
			ca_cert=$(uci get ipsec.$configname.ca_cert)

			echo -e "\tauthby=pubkey" >> "$conf"
			echo -e "\tleftcert=$left_cert" >> "$conf"
			echo -e "\tleftid=$left_id" >> "$conf"
			echo -e "\trightid=$right_id" >> "$conf"

			if [ "$certkey" == "RSA" ]; then
				echo -e "$right_id : RSA $left_key" >> "$secret"
			elif [ "$certkey" == "ECDSA" ]; then
				echo -e "$right_id : ECDSA $left_key" >> "$secret"
			fi
			ipsec rereadall
		elif [ "$keymode" == "rsasigscep" ]; then
			#Copy the scep cert to ipsec.d
			cp "$SCEP_CERT_PATH/$certname/$certname.$scepcerttype" "$IPSEC_PATH/certs/$certname.$scepcerttype"
			cp "$SCEP_CERT_PATH/$certname/$certname-ca.$scepcerttype" "$IPSEC_PATH/cacerts/$certname-ca.$scepcerttype"
			cp "$SCEP_CERT_PATH/$certname/$certname-key.key" "$IPSEC_PATH/private/$certname-key.key"

			#Load the certificates
			ipsec rereadall

			if [ "$scepcerttype" == "pem" ]; then
				left_cert="$IPSEC_PATH/certs/$certname.pem"
				left_key="$IPSEC_PATH/private/$certname-key.key"
				ca_cert="$IPSEC_PATH/cacerts/$certname-ca.pem"
			elif [ "$scepcerttype" == "der" ]; then
				left_cert="$IPSEC_PATH/certs/$certname.der"
				left_key="$IPSEC_PATH/private/$certname-key.key"
				ca_cert="$IPSEC_PATH/cacerts/$certname-ca.der"
			fi

			echo -e "\tauthby=pubkey" >> "$conf"
			echo -e "\tleftcert=$left_cert" >> "$conf"
			if [ "$left_id_sub" != "" ]; then
				echo -e "\tleftid=$left_id_sub" >> "$conf"
			fi
			if [ "$right_id" != "" ]; then
				echo -e "\trightid=$right_id" >> "$conf"
			fi

			echo -e "$left_id_sub : RSA $left_key" >> "$secret"
		fi

		if [ "$ikemod" == "aggressive" ]; then 
			echo -e "\taggressive=yes" >> "$conf"
		fi

		if [ "$dpddelay" != "" ]; then 
			echo -e "\tdpddelay=$dpddelay" >> "$conf" 
		fi

		if [ "$dpdtimeout" != "" ]; then
			echo -e "\tdpdtimeout=$dpdtimeout" >> "$conf"
		fi

		if [ "$force_encaps" == "1" ]; then
			echo -e "\tforceencaps=yes" >> "$conf"
		fi

		if [ "$natenable" == "1" ]; then
			echo -e "\tleftfirewall=no" >> "$conf"
		else
			echo -e "\tleftfirewall=yes" >> "$conf"
		fi

		#update ipsec config
		ipsec update
	fi
}

config_update() {
	local configname="$1"
	local CONFIG="$IPSEC_VAR_PATH/$configname"

	config_load ipsec
	config_get proto "$configname" proto
	config_get conn "$configname" conn
	config_get enable "$configname" enable

	if [ "$enable" == "1" ]; then
		configavailable=1
		update_ipsec_config $configname
	else
		mkdir -p "$CONFIG"
		echo "DISABLED" > "$CONFIG/status"
	fi
}

Reconnect() {
	local configname="$1"
	/usr/bin/logger -t IPSEC -p info  "Reconnect: $configname"
	avail=$(uci get ipsec."$configname".conn | xargs echo -n)
	if [ "$avail" != "$configname" ]
		then
		echo "No Such Interface"
		exit 1
	fi

	Disconnect $configname

	time=$(uci get ipsec."$configname".dpdtime | xargs echo -n)
	if [ "$time" == "" ]; then 
		time=5
	fi

	#sleep $time
	Connect $configname
}

delete_ipsec_conf() {
	local configname="$1"
	local CONFIG="$IPSEC_VAR_PATH/$configname"

	/usr/bin/logger -t IPSEC -p info  "delete_ipsec_conf: $configname"
	#Delete single conf file
	[ -e "$CONFIG.conf" ] && rm -rf "$CONFIG.conf"
	[ -e "$CONFIG.secrets" ] && rm -rf "$CONFIG.secrets"

	#Delete the var config path
	rm -rf "$CONFIG"

	maintainer=$(ps w | grep -i "/usr/sbin/ipsec_maintainer.sh $configname" | grep -v grep | awk '{print $1}')
	if [ "$maintainer" != "" ]; then
		/usr/bin/logger -t IPSEC -p info  "killing maintainer: $configname"
		kill -9 $maintainer
		rm -rf /var/run/ipsec_maintainer_${configname}.pid
	fi

	old_route=$(cat "$CONFIG/old_route" 2>/dev/null)
	[ -n "$old_route" ] && /sbin/ip route delete $old_route 2>/dev/null
}

Disconnect() {
	/usr/bin/logger -t IPSEC -p info  "Disconnect: $configname"
	local configname="$1"
	avail=$(uci get ipsec.$configname.conn | xargs echo -n)
	if [ "$avail" != "$configname" ]; then
		echo "No Such Interface"
		exit 1
	fi

	#Enable to 0, on Disconnect
	uci set ipsec.$configname.enable=0
	uci commit ipsec.$configname.enable

	#Down the ipsec interface
	config_load ipsec
	config_get conntype "$configname" conntype

	if [ "$conntype" == "initiate" ]; then
		/usr/sbin/ipsec down "$configname"
	fi

	delete_ipsec_conf "$configname"

	#Delete nat rules for $configname
	handle_delete_ipt_nat_rule $configname

	#Stop ipsec
	stop_ipsec
	# End of Disconnect
}

Connect() {
	local configname="$1"
	local CONFIG="$IPSEC_VAR_PATH/$configname"

	/usr/bin/logger -t IPSEC -p info  "Connect: $configname"

	avail=$(uci get ipsec.$configname.conn | xargs echo -n)

	if [ "$avail" != "$configname" ]; then
		echo "No Such Interface"
		exit 1
	fi

	#Enable to 1, on Connect
	uci set ipsec.$configname.enable=1
	uci commit ipsec.$configname.enable

	mkdir -p "$IPSEC_VAR_PATH"
	mkdir -p "$CONFIG"
	echo "CONNECTING" > "$CONFIG/status"

	#Interface is already connected, disconnect & connect it back
	#Disconnect $configname

	#update configuration
	config_update $configname

	#update wan policy
	[ -f /usr/sbin/ipsec_maintainer.sh ] && /usr/sbin/ipsec_policy.sh $configname

	#Start ipsec
	start_ipsec

	ipsec update
	sleep 5

	config_load ipsec
	config_get conntype "$configname" conntype

	if [ "$conntype" == "initiate" ]; then
		echo "CONNECTING" > "$CONFIG/status"
		/usr/bin/logger -t IPSEC -p info  "Initiating ipsec configname: $configname"
		/usr/sbin/ipsec up $configname &
	fi

	[ -e "/usr/sbin/ipsec_maintainer.sh" ] && /usr/sbin/ipsec_maintainer.sh $configname &

	[ -e "/usr/sbin/ipsec_uptime.sh" ] && /usr/sbin/ipsec_uptime.sh &

	[ -e "/usr/sbin/ipsec_watchdog.sh" ] && /usr/sbin/ipsec_watchdog.sh &
	
	#End of Connect
}

reload_update_ipsec_config() {
	local configname="$1"
	local CONFIG="$IPSEC_VAR_PATH/$configname"

	mkdir -p "$CONFIG"

	/usr/bin/logger -t IPSEC -p info  "reload_update_ipsec_config: $configname"
	config_load ipsec
	config_get enable "$configname" enable

	if [ "$enable" == "1" ]; then
		configavailable=1
		update_ipsec_config $configname
	else
		echo "DISABLED" > "$CONFIG/status"
	fi
}

Delete() {
	local configname="$1"
	/usr/bin/logger -t IPSEC -p info  "Connect: $configname"

	avail=$(uci get ipsec.$configname.conn | xargs echo -n)
	if [ "$avail" != "$configname" ];then
		echo "No Such Interface"
		exit 1
	fi
	
	#Disconnect connection
	Disconnect "$configname"

	delete_ipsec_conf "$configname"
	
	/usr/sbin/ipsec update
	#End of Delete operation
}

connect_ipsec() {
	local configname="$1"
	/usr/bin/logger -t IPSEC -p info  "connect_ipsec: $configname"
	config_load ipsec
	config_get enable "$configname" enable

	if [  "$enable" == "1" ]; then
		Connect $configname &
	fi
}

StartService() {
	/usr/bin/logger -t IPSEC -p info  "Ipsec Service Start"
	#Add ipt chains
	handle_ipt_start_service

	mkdir -p "$IPSEC_VAR_PATH"

	#Start config
	config_load ipsec
	config_foreach connect_ipsec ipsec
	/usr/bin/logger -t IPSEC -p info  "Ipsec Service Start completed"
	#End StartService
}

disconnect_ipsec() {
	local configname="$1"
	/usr/bin/logger -t IPSEC -p info  "disconnect_ipsec"
	config_load ipsec
	config_get conntype "$configname" conntype
	config_get enable "$configname" enable
	if [  "$enable" == "1" ]; then
		Disconnect $configname
	fi

	#Delete ipsec conf file
	delete_ipsec_conf "$configname"
}

StopService() {
	/usr/bin/logger -t IPSEC -p info  "Stop Ipsec Service"
	config_load ipsec
	config_foreach disconnect_ipsec ipsec
	#stop_ipsec

	#Remove uptime
	uptime=$(ps w | grep -i "/usr/sbin/ipsec_uptime.sh" | grep -v grep | awk '{print $1}')
	if [ "$uptime" != "" ]; then
		kill -9 $uptime > /dev/null 2>&1
	fi

	#Delete ipt chain
	handle_ipt_stop_service

	starterpid=$(ps w | grep /usr/lib/ipsec/starter | grep -v grep | awk '{print$1}' | xargs echo -n)
	charonpid=$(ps w | grep /usr/lib/ipsec/charon | grep -v grep | awk '{print$1}' | xargs echo -n)

	if [[ "$starterpid" != "" || "$charonpid" != "" ]]; then
		ipsec stop
		sleep 2
	fi
	/usr/bin/logger -t IPSEC -p info  "Stop Ipsec Service completed"
	#End of StopService
}

relaod_connect_ipsec() {
	local configname="$1"
	local CONFIG="$IPSEC_VAR_PATH/$configname"
	/usr/bin/logger -t IPSEC -p info  "connect_ipsec: $configname"
	config_load ipsec
	config_get enable "$configname" enable
	config_get conntype "$configname" conntype

	if [ "$enable" == "1" ]; then
		local status=$(cat $IPSEC_VAR_PATH/status | xargs echo -n)
		if [ "$status" != "ESTABLISHED" ]; then
			Disconnect "$configname"
			Connect "$configname"
		fi
	else
		Disconnect "$configname"
	fi
}

ReloadService() {
	/usr/bin/logger -t IPSEC -p info  "Reload Ipsec Service"
	config_load ipsec
	config_foreach reload_update_ipsec_config ipsec
	ipsec rereadall
	sleep 2
	ipsec update
	sleep 2
	ipsec reload
	sleep 2

	config_load ipsec
	config_foreach relaod_connect_ipsec ipsec
	/usr/bin/logger -t IPSEC -p info  "Reload Ipsec Service completed"
}

start_ipsec() {
	/usr/bin/logger -t IPSEC -p info  "Starting Ipsec"
	config_load ipsec
	config_foreach check_config_available ipsec

	handle_ipt_add_respond_rule


	oldstarterpid=$(cat /tmp/run/starter.charon.pid 2>/dev/null)
	oldcharonpid=$(cat /tmp/run/charon.pid 2>/dev/null)
	starterpid=$(ps w | grep /usr/lib/ipsec/starter | grep -v grep | awk '{print$1}' | xargs echo -n)
	charonpid=$(ps w | grep /usr/lib/ipsec/charon | grep -v grep | awk '{print$1}' | xargs echo -n)


	if [[ "$starterpid" != "oldstarterpid" || "$charonpid" != "oldcharonpid" ]]; then
		if [ $configavailable -eq 1 ]; then
			/usr/bin/logger -t IPSEC -p info "Starting ipsec"
			ipsec restart
			sleep 5
		else
			/usr/bin/logger -t IPSEC -p info  "Ipsec Not running. No configuration available. not restarting"
		fi
	else
		/usr/bin/logger -t IPSEC -p info  "Ipsec Already Running"
	fi
	while true; do
		#ipsec taking some time to start
		starterpid=$(cat /tmp/run/starter.charon.pid 2>/dev/null)
		charonpid=$(cat /tmp/run/charon.pid 2>/dev/null)
		if [[ "$starterpid" != "" && "$charonpid" != "" ]]; then
			/usr/bin/logger -t IPSEC -p info  "Starting Ipsec finished"
			break
		else
			sleep 3
		fi
	done
}

stop_ipsec() {
	/usr/bin/logger -t IPSEC -p info  "Stopping ipsec"
	configavailable=0
	config_load ipsec
	config_foreach check_config_available ipsec
	handle_ipt_delete_respond_rule

	if [ $configavailable -eq 0 ]; then
		starterpid=$(ps w | grep /usr/lib/ipsec/starter | grep -v grep | awk '{print$1}' | xargs echo -n)
		charonpid=$(ps w | grep /usr/lib/ipsec/charon | grep -v grep | awk '{print$1}' | xargs echo -n)

		if [[ "$starterpid" != "" || "$charonpid" != "" ]]; then
			ipsec stop
			sleep 2
		fi
	fi
	/usr/bin/logger -t IPSEC -p info  "Stopping ipsec finished"
}

main() {
	/usr/bin/logger -t IPSEC -p info  "Received command: $@"
	commd="$1"

	option="$commd"

	case "$option" in 
		Connect | Disconnect | Delete | Reconnect)
			configname="$2"
			if [ $# -eq 2 ]
				then
				$commd $configname
			fi
		;;

		StartSrv)
			StartService
		;;

		StopSrv)
			StopService
		;;

		ReloadSrv)
			ReloadService
		;;
	esac

	exit 0
}

main "$@"
