#!/bin/sh

. ../common/ajax_common


if [ "${PALANG}" = "en" ]; then
	LANG001="Error"		#ʧ
	LANG002="Success"	#ɹ
	LANG003="Add_Port_Mapping"	#ö˿ӳ
	LANG004="Add_Port_Mapping"	#Ӷ˿ӳ
	LANG005="num"	#
	LANG006="ok"	#ɹ
	LANG007="fail"	#ʧ
	LANG008="Add Success"	#
	LANG009="Delete_Port_Mapping"	#ɾ˿ӳ
	LANG010="Enable_Port_Mapping"	#ö˿ӳ
	LANG011="Disable_Port_Mapping"	#ö˿ӳ
	LANG012="Enable_Port_Mapping"	#ö˿ӳ
	LANG013="Disable_Port_Mapping"	#ö˿ӳ
	LANG014="Delete_Port_Mapping"	#ɾ˿ӳ
	LANG015="Import_Port_Mapping"	#˿ӳ
	LANG016="Import Num"			#
	LANG017="Import Success"		#
fi


list_proxy_dict()
{
	${FLOWEYE} nat listproxy type=wan | awk \
	'BEGIN{
		dot = "";
		printf "{";	
	}{
		printf "%s\"wan_%s\":{", dot, $3;
		printf "\"type\":\"%s\",", $1;
		printf "\"ip\":\"%s\"", $5;
		printf "}";
		if(dot == "") dot = ",";
	}END{
		printf "}";
	}'
}


list_portmap()
{
	[ "${CGI_page}" = "" ] && CGI_page=1
	[ "${CGI_limit}" = "" ] && CGI_limit=100

	end=$(( ${CGI_page} * ${CGI_limit} ))
	start=$(( ${end} - ${CGI_limit} ))

	${FLOWEYE} nat listportmap | grep "${CGI_keyword}" | awk \
	-v wan_name="${CGI_wan_name}" -v disable="${CGI_disable}" \
	-v start=${start} -v end=${end} \
	'BEGIN{
		row = 0;
		dot = "";
		printf "{\"data\":[";
	}{
		if (wan_name != "" && $3 != wan_name) next;
		if (disable != "" && $15 != disable) next;

		row++;
		if( row > end  || row < start ) next;

		gsub("\r", " ", $NF);
		gsub("%20", " ", $NF);

		col = 1;

		printf "%s", dot;
		printf "{";
		printf "\"id\":\"%s\",", $(col++);
		printf "\"wan_id\":\"%s\",", $(col++);
		printf "\"wan_name\":\"%s\",", $(col++);
		printf "\"wan_type\":\"%s\",", $(col++);
		printf "\"dst\":\"%s\",", $(col++);
		printf "\"port\":\"%s\",", $(col++);
		printf "\"proto\":\"%s\",", $(col++);
		printf "\"maptype\":\"%s\",", $(col++);
		printf "\"mapip\":\"%s\",", $(col++);
		printf "\"mapport\":\"%s\",", $(col++);
		printf "\"mac\":\"%s\",", $(col++);
		printf "\"gateway\":\"%s\",", $(col++);
		printf "\"count\":\"%s\",", $(col++);
		printf "\"rtif\":\"%s\",", $(col++);
		printf "\"disable\":\"%s\",", $(col++);
		printf "\"snattype\":\"%s\",", $(col++);
		printf "\"snatip\":\"%s\",", $(col++);
		printf "\"src\":\"%s\",", $(col++);
		printf "\"desc\":\"%s\"", $(col++);
		printf "}";
		if ( dot == "" ) dot = ",";
	}END{
		printf "],\"total\":\"%s\"}", row;
	}'
}


load_portmap_list()
{
	printf "{"
	printf "\"policy\":`list_portmap`"
	printf ",\"proxy\":`list_proxy_dict`"
	printf "}"
}


list_map_session()
{
	${FLOWEYE} nat listnpmflow id=${CGI_id} | grep "${CGI_keyword}" | awk \
	'BEGIN{
		dot = "";
		printf "[";
	}{
		col = 1;
		printf "%s", dot;
		printf "{";
		printf "\"birth\":\"%s\",", $(col++);
		printf "\"appname\":\"%s\",", $(col++);
		printf "\"proto\":\"%s\",", $(col++);
		printf "\"src\":\"%s\",", $(col++);
		printf "\"sport\":\"%s\",", $(col++);
		printf "\"dst\":\"%s\",", $(col++);
		printf "\"dport\":\"%s\",", $(col++);
		printf "\"mapip\":\"%s\",", $(col++);
		printf "\"mapport\":\"%s\",", $(col++);
		printf "\"upbytes\":\"%s\",", $(col++);
		printf "\"downbytes\":\"%s\"", $(col++);
		printf "}";
		if(dot == "") dot = ",";
	}END{
		printf "]";
	}'
}


list_server()
{
	[ "${CGI_group}" != "" ] && args="group=${CGI_group}"
	
	printf "["
	${FLOWEYE} server list ${args} 
	printf "]"
}


list_svrgroup()
{
	${FLOWEYE} svrgroup list | awk \
	'BEGIN{
		dot="";
		printf "[";
	}{
		printf "%s{", dot;
		printf "\"id\":%d,", $1;
		printf "\"name\":\"%s\",", $2;
		printf "\"svrcnt\":\"%s\",", $3;
		printf "\"type\":\"%s\",", $4;
		printf "\"flowcnt\":\"%s\",", $5;
		printf "\"missed\":\"%s\",", $6;
		printf "\"bpsin\":\"%s\",", $7;
		printf "\"bpsout\":\"%s\"", $8;
		printf "}";
		if(dot == "") dot=","
	}END{
		printf "]";
	}'
}


get_portmap()
{
	${FLOWEYE} nat getportmap id=${CGI_id} | awk -F "=" \
	'BEGIN{
		dot = "";
		printf "{";
	}{
		if($1 == "note") gsub("%20", " ", $2);
		
		printf "%s", dot;
		printf "\"%s\":\"%s\"", $1, $2;
		if (dot == "") dot = ",";
	}END{
		printf "}";
	}'
}


load_add_portmap_env()
{
	. ../common/ajax_object_lib

	printf "{"
	printf "\"server\":`list_server`"
	printf ",\"svrgroup\":`list_svrgroup`"
	printf ",\"wangroup\":`lib_wangroup_list`"
	printf ",\"proxy\":`lib_proxy_list`"
	printf ",\"pxy_dict\":`list_proxy_dict`"
	
	if [ "${CGI_id}" != "" ]; then
		printf ",\"policy\":`get_portmap`"
	fi

	printf "}"
}


add_portmap()
{
	[ "${CGI_gateway}" = "" ] && CGI_gateway="0.0.0.0"
	[ "${CGI_dst}" = "" ] && CGI_dst="0.0.0.0"
	[ "${CGI_mapport}" = "" ] && CGI_mapport=0
	
	if [ "${CGI_maptype}" = "svr" ]; then
		[ "${CGI_server}" = "" ] && retjson 1 "NO_SERVER"
		CGI_mapip="${CGI_server}"
	elif [ "${CGI_maptype}" = "sg" ]; then
		[ "${CGI_svrgrp}" = "" ] && retjson 1 "NO_SERVER_GROUP"
		CGI_mapip="${CGI_svrgrp}"
	fi

	if [ "${CGI_action}" = "edit_portmap" ]; then
		action="setportmap id=${CGI_old_id} newid=${CGI_id}"
	else
		action="addportmap"
		[ "${CGI_id}" != "" ] && action="${action} id=${CGI_id}"
	fi

	cmdargs="${action} wan=${CGI_wan_name} dst=${CGI_dst} port=${CGI_port} proto=${CGI_proto}"
	cmdargs="${cmdargs} mapip=${CGI_mapip} mapport=${CGI_mapport} gateway=${CGI_gateway}"
	cmdargs="${cmdargs} src=${CGI_submit_srcip} nomapback=${CGI_nomapback} disable=${CGI_disable}"

	if [ "${CGI_snattype}" = "ip" ]; then
		cmdargs="${cmdargs} snattype=${CGI_snattype} snatip=${CGI_snatip}"
	else
		cmdargs="${cmdargs} snattype=${CGI_snattype}"
	fi

	[ "${CGI_note}" = "" ] && CGI_note="NULL"
	CGI_note=`echo ${CGI_note} | sed -r 's/ /\%20/g'`
	[ "${CGI_note}" != "" ] && cmdargs="${cmdargs} note=${CGI_note}"

	errmsg=`${FLOWEYE} nat ${cmdargs}`

	if [ "$?" != "0" ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "nat ${cmdargs}"
		[ "${CGI_id}" = "" ] && CGI_id="${errmsg}" # Ӷ˿ӳ䣬floweyeԶID
		WEB_LOGGER "${LANG003:=ö˿ӳ}" "${cmdargs}"
		retjson 0 "${LANG002:=ɹ}" "{\"id\":\"${CGI_id}\"}"
	fi
}


addm_portmap()
{
	init=0
	port=${CGI_port}
	mapip=${CGI_mapip}
	mapport=${CGI_mapport}

	ok=0
	fail=0

	while [ ${init} -lt ${CGI_num} ];
	do
		cmdargs="wan=${CGI_wan_name} proto=${CGI_proto} gateway=${CGI_gateway} disable=${CGI_disable}"
		cmdargs="${cmdargs} port=${port} mapip=${mapip} mapport=${mapport}"

		errmsg=`${FLOWEYE} nat addportmap ${cmdargs}`

		if [ $? -ne 0 ]; then
			fail=$((${fail} + 1))
		else
			sync_floweye "nat addportmap ${cmdargs}"
			ok=$((${ok} + 1))
		fi

		init=$((${init} + 1))
		port=$((${port} + 1))
		
		[ "${CGI_mapport_add}" = "on" ] && mapport=$((${mapport} +1))

		if [ "${CGI_mapip_add}" = "on" ]; then
			addr1=`echo ${mapip} | cut -d"." -f1`
			addr2=`echo ${mapip} | cut -d"." -f2`
			addr3=`echo ${mapip} | cut -d"." -f3`
			addr4=`echo ${mapip} | cut -d"." -f4`

			addr4=$((${addr4}+1))

			if [ ${addr4} -gt 254 ]; then 
				addr4=1
				addr3=$((${addr3}+1))
				if [ ${addr3} -gt 255 ]; then 
					addr3=1
					addr2=$(( ${addr2}+1 ))
				fi
			fi
			mapip="${addr1}.${addr2}.${addr3}.${addr4}"
		fi
	done

	WEB_LOGGER "${LANG004:=Ӷ˿ӳ}" "${LANG005:=}=${CGI_num},${LANG006:=ɹ}${ok},${LANG007:=ʧ}:${fail}"
	retjson 0 "${LANG008:=},${LANG006:=ɹ}${ok},${LANG007:=ʧ}:${fail}"
}


rmv_portmap()
{
	errmsg=`${FLOWEYE} nat rmvportmap id=${CGI_id}`

	if [ "$?" != "0" ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "nat rmvportmap id=${CGI_id}"
		WEB_LOGGER "${LANG009:=ɾ˿ӳ}" "id=${CGI_id}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


enable_portmap()
{
	errmsg=`${FLOWEYE} nat setportmap id=${CGI_id} disable=0`

	if [ "$?" != "0" ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "nat setportmap id=${CGI_id} disable=0"
		WEB_LOGGER "${LANG010:=ö˿ӳ}" "id=${CGI_id}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


disable_portmap()
{
	errmsg=`${FLOWEYE} nat setportmap id=${CGI_id} disable=1`

	if [ "$?" != "0" ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "nat setportmap id=${CGI_id} disable=1"
		WEB_LOGGER "${LANG011:=ö˿ӳ}" "id=${CGI_id}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


btnenable_portmap()
{
	for id in `echo ${CGI_items} | tr ";" " "`
	do
		errmsg=`${FLOWEYE} nat setportmap id=${id} disable=0`
		[ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}${errmsg}"
		sync_floweye "nat setportmap id=${id} disable=0"
	done

	WEB_LOGGER "${LANG012:=ö˿ӳ}" "ids=${CGI_items}"
	retjson 0 "${LANG002:=ɹ}"
}


btndisable_portmap()
{
	for id in `echo ${CGI_items} | tr ";" " "`
	do
		errmsg=`${FLOWEYE} nat setportmap id=${id} disable=1`
		[ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}${errmsg}"
		sync_floweye "nat setportmap id=${id} disable=1"
	done

	WEB_LOGGER "${LANG013:=ö˿ӳ}" "ids=${CGI_items}"
	retjson 0 "${LANG002:=ɹ}"
}


btnremove_portmap()
{
	for id in `echo ${CGI_items} | tr ";" " "`
	do
		errmsg=`${FLOWEYE} nat rmvportmap id=${id}`
		[ $? -ne 0 ] && retjson 1 "${LANG001:=ʧ}${errmsg}"
		sync_floweye "nat rmvportmap id=${id}"
	done

	WEB_LOGGER "${LANG014:=ɾ˿ӳ}" "ids=${CGI_items}"
	retjson 0 "${LANG002:=ɹ}"
}


export_portmap()
{
	file_name="pa_portmap.conf"
	file_path="${WEB_DOWNLOAD}/${file_name}"
	
	mkdir -p ${WEB_DOWNLOAD}

	grep "^npm " "${PGETC}/panabit.conf" | cut -d" " -f2- > ${file_path}

	retjson 0 "${LANG002:=ɹ}" "{\"file_name\":\"${file_name}\"}"
}


import_portmap()
{
	[ "${CGI_file}" = "" ] && retjson 1 "NO_FILE"

	errmsg=`grep " wan=" ${CGI_file}`
	if [ "${errmsg}" = "" ]; then
		rm -rf "$CGI_file}"
		retjson 1 "INV_FILE"
	fi

	allwan=`${FLOWEYE} nat listproxy type=wan | awk '{printf ";%s;", $3;}'`
	wangrp=`${FLOWEYE} wangroup list | awk '{printf ";_wg.%s;", $2;}'`

	errmsg=`awk -v allwan="${allwan};${wangrp}" '{
		#·ȥ
		for(i = 1; i <= length($0); i++){
			split($i, item, "=");
			if(item[1] == "wan"){
				wans[item[2]] = 1;
				break;
			}
		}
	} END {
		#У·Ƿ
		for(wan in wans){
			if (match(allwan, ";" wan ";") <= 0)
				err_wans[wan] = 1;
		}
		#ûвڵ·˳
		if(length(err_wans) == 0)
			exit(0);
		#ڵ·
		dot = "";
		printf "[";
		for(wan in err_wans){
			printf "%s\"%s\"", dot, wan;
			if(dot == "") dot = ",";
		}
		printf "]";
		exit(1);
	}' ${CGI_file}`
	
	if [ $? -ne 0 ]; then
		rm -rf ${CGI_file}
		retjson 2 "ĲУӳ·ڣӺٵ" ${errmsg}
	fi

	total=`cat ${CGI_file} | wc -l`
	err_result=`${FLOWEYE} portmap load file=${CGI_file} append=${CGI_append} rollback=1 | awk \
	'BEGIN{
		dot = "";
		printf "[";
	}{
		printf "%s\"%s\"", dot, $0;
		if(dot == "") dot = ",";
	}END{
		printf "]";
	}'`

	rm -rf ${CGI_file}

	if [ "${err_result}" != "[]" ]; then
		retjson 3 "ĲԲ㵼" "${err_result}"
	else
		WEB_LOGGER "${LANG015:=˿ӳ}"
		retjson 0 "${LANG002:=ɹ}" "{\"total\":${total}}"
	fi
}


clear_import_stat()
{
	import_stat="${RAMDISK}/tmp/import_portmap.stat"
	[ -f "${import_stat}" ] && rm -rf ${import_stat}
}


load_nat_stat()
{
	stat=`${FLOWEYE} nat stat | grep ^nhinstall | cut -d"=" -f2`

	printf "{\"nhinstall\":${stat}}"
}


set_nat_stat()
{
	[ "${CGI_nhinstall}" = "on" ] && stat=1 || stat=0
	errmsg=`${FLOWEYE} nat config nhinstall=${stat}`

	if [ $? -ne 0 ]; then
		retjson 1 "ʧܣ${errmsg}"
	else
		sync_floweye "nat config nhinstall=${stat}"
		WEB_LOGGER "ö˿ڻ" "nhinstall=${stat}"
		retjson 0 "ɹ"
	fi
}


case "${CGI_action}" in
	"list_portmap")
		retjson 0 "OK" "`list_portmap`"
		;;
	
	"load_portmap_list")
		retjson 0 "OK" "`load_portmap_list`"
		;;

	"load_add_portmap_env")
		retjson 0 "OK" "`load_add_portmap_env`"
		;;
	
	"list_map_session")
		retjson 0 "OK" "`list_map_session`"
		;;

	"add_portmap"|"edit_portmap")
		action_check
		add_portmap
		;;
	
	"addm_portmap")
		action_check
		addm_portmap
		;;

	"rmv_portmap")
		action_check
		rmv_portmap
		;;
	
	"enable_portmap")
		action_check
		enable_portmap
		;;
	
	"disable_portmap")
		action_check
		disable_portmap
		;;

	"btndisable_portmap")
		action_check
		btndisable_portmap
		;;

	"btnenable_portmap")
		action_check
		btnenable_portmap
		;;
	
	"btnremove_portmap")
		action_check
		btnremove_portmap
		;;

	"export_portmap")
		action_check
		export_portmap
		;;
	
	"import_portmap")
		action_check
		import_portmap
		;;

	"clear_import_stat")
		action_check
		clear_import_stat
		;;
		
	"load_nat_stat")
		retjson 0 "OK" "`load_nat_stat`"
		;;

	"set_nat_stat")
		action_check
		set_nat_stat
		;;

	*)
		retjson 1 "UNKNOW_ACTION"
		;;
		
esac
