#!/bin/sh

. ../common/ajax_common

if [ "${PALANG}" = "en" ]; then
	LANG001="Error"		#ʧ
	LANG002="Success"	#ɹ
	LANG003="Set_PPPOE_Accunt"		#û˺
	LANG004="Unbind_Account_MAC"	#PPPOE˺MAC
	LANG005="num"	#
	LANG006="Del_PPPOE_Account"		#ɾPPPOE˺
	LANG007="Enable_PPPOE_Account"	#PPPOE˺
	LANG008="Disable_PPPOE_Account"	#PPPOE˺
	LANG009="Set_PPPOE_Account"		#޸˺
	LANG010="Export_PPPOE_Account"	#PPPOE˺
	LANG011="Proxy_Account"			#˺
	LANG012="PPPOE_Account"			#˺
fi


list_pppoe_account()
{
	case "${CGI_sort_key}" in
		"pool_name")
			sort_key="-k1"
			;;

		"account")
			sort_key="-k3"
			;;

		"online_ip")
			sort_key="-k5"
			;;

		"online_mac")
			sort_key="-k6"
			;;

		"start")
			sort_key="-k7"
			;;

		"end")
			sort_key="-nk9"
			;;

		"offtime")
			sort_key="-k10"
			;;
			
		"bind_mac")
			sort_key="-k13"
			;;

		"online_cnt")
			sort_key="-nk14"
			;;

		"bind_ip")
			sort_key="-k16"
			;;

		"out_if")
			sort_key="-k17"
			;;
			
		"out_vlan1")
			sort_key="-nk18"
			;;

		*)
			sort_key="-nk9"
			;;
	esac

	[ "${CGI_sort_type}" = "desc" ] && sort_type="-r"

	[ "${CGI_acct_type}" = "" ] && CGI_acct_type="local"

	[ "${CGI_limit}" = "" ] && CGI_limit=100
	[ "${CGI_page}"  = "" ] && CGI_page=1
	end=$(( ${CGI_page} * ${CGI_limit} ))
	start=$(( ${end} - ${CGI_limit} ))

	${FLOWEYE} pppoeacct list poolid=${CGI_pool_id} | sort ${sort_type} ${sort_key} | grep -i "${CGI_keyword}" | awk \
	-v start=${start} -v end=${end} -v type="${CGI_acct_type}" -v status="${CGI_status}" -v expire="${CGI_expire}" \
	'BEGIN{
		row = 0;
		dot = "";
		printf "{\"data\":[";
	}{
		if($17 == "NULL" && type == "proxy") next;
		if($17 != "NULL" && type == "local") next;
		if(status != "" && $11 != status ) next;
		
		if(expire == "expire" && $9 >= 0)
			next;
		else if(expire == "inuse" && $9 < 0)
			next;
		else if(expire == "soon" && ($9 > 2592000 || $9 < 0))
			next;

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

		gsub("%20", " ", $20);

		col = 1;
		printf "%s", dot;
		printf "{";
		printf "\"pool_id\":\"%s\",", $(col++);
		printf "\"pool_name\":\"%s\",",$(col++);
		printf "\"account\":\"%s\",", $(col++);
		printf "\"password\":\"%s\",", $(col++);
		printf "\"online_ip\":\"%s\",", $(col++);
		printf "\"online_mac\":\"%s\",", $(col++);
		printf "\"start\":\"%s\",", $(col++);
		printf "\"end\":\"%s\",", $(col++);
		printf "\"lef_time\":\"%s\",", $(col++);
		printf "\"offtime\":\"%s\",", $(col++);
		printf "\"disable\":\"%s\",", $(col++);
		printf "\"login_fail\":\"%s\",", $(col++);
		printf "\"bind_mac\":\"%s\",", $(col++);
		printf "\"online_cnt\":\"%s\",", $(col++);
		printf "\"max_online\":\"%s\",", $(col++);
		printf "\"bind_ip\":\"%s\",", $(col++);
		printf "\"out_if\":\"%s\",", $(col++);
		printf "\"out_vlan1\":\"%s\",", $(col++);
		printf "\"out_vlan2\":\"%s\",", $(col++);
		printf "\"more_info\":\"%s\",", $(col++);
		printf "\"acct_type\":\"%s\"", ($17 == "NULL" ? "local" : "proxy");
		printf "}";

		if(dot == "") dot = ",";
	}END{
		printf "],\"total\":\"%s\"}", row;
	}'
}


add_user_account()
{
	[ "${CGI_acct_type}" = "proxy" ] && acct_type="${LANG011:=˺}" || acct_type="${LANG012:=˺}"
	[ "${CGI_action}" = "add_user_account" ] && action="add" || action="set"

	CGI_cname=`echo ${CGI_cname} | sed -r 's/ /\%20/g'`
	CGI_other=`echo ${CGI_other} | sed -r 's/ /\%20/g'`

	[ "${CGI_maxonline}" = "" ] && CGI_maxonline="1"
	[ "${CGI_bindmac}" = "" ] && CGI_bindmac="00-00-00-00-00-00"
	[ "${CGI_bindip}" = "" ] && CGI_bindip="0.0.0.0"

	cmdargs="poolid=${CGI_poolid} name=${CGI_name} start=${CGI_start} expire=${CGI_expire} maxonline=${CGI_maxonline}"

	if [ "${CGI_acct_type}" = "local" ]; then
		cmdargs="${cmdargs} password=${CGI_passwd} bindmac=${CGI_bindmac} bindip=${CGI_bindip} outvlan=${CGI_outvlan}"
	else
		cmdargs="${cmdargs} password=_123456_ outif=${CGI_outif} outvlan=${CGI_outvlan} outvlan1=${CGI_outvlan1}"
	fi

	cmdargs="${cmdargs} phone=${CGI_phone} card=${CGI_card} cname=${CGI_cname} other=${CGI_other}"

	errmsg=`${FLOWEYE} pppoeacct ${action} ${cmdargs}`

	if [ $? -ne 0 ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "pppoeacct ${action} ${cmdargs}"
		WEB_LOGGER "${LANG003:=û˺}" "action=${action} ${cmdargs}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


addm_user_account()
{
	num=${CGI_start_num}
	today=`date +"%Y-%m-%d"`

	for line in `echo ${CGI_items} | tr "+" " "`
	do					
		name=`echo ${line} | cut -d ";" -f1`
		pswd=`echo ${line} | cut -d ";" -f2`
		pool=`echo ${line} | cut -d ";" -f3`
		expire=`echo ${line} | cut -d ";" -f4`
		cname=`echo ${line} | cut -d ";" -f5`
		idcard=`echo ${line} | cut -d ";" -f6`
		telphone=`echo ${line} | cut -d ";" -f7`
		other=`echo ${line} | cut -d ";" -f8`

		cmdargs="name=${name} poolid=${pool} start=${today} expire=${expire} password=${pswd}"
		cmdargs="${cmdargs} phone=${telphone} card=${idcard} cname=${cname} other=${other}"

		errmsg=`${FLOWEYE} pppoeacct add ${cmdargs}`

		if [ $? -ne 0 ]; then
			if [ "${errmsg}" = "ACCOUNT_EXIST" ]; then
				[ "${CGI_exist}" = "cover" ] && ${FLOWEYE} pppoeacct set ${cmdargs}
			else
				fail=$((${num}+1))
				retjson 1 "${fail}${errmsg}ѳɹ${num}"
			fi
		fi

		sync_floweye "pppoeacct add ${cmdargs}"
		num=$((${num} + 1))
	done

	retjson 0 "OK"
}


unbind_mac()
{
	num=0
	cmdargs=""

	for acct in `echo ${CGI_accounts} | tr "+" " "`
	do
		cmdargs="${cmdargs} unbindmac=${acct}"
		num=$((${num}+1))
	done

	errmsg=`${FLOWEYE} pppoeacct config ${cmdargs}`

	if [ $? -ne 0 ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "pppoeacct config ${cmdargs}"
		WEB_LOGGER "${LANG004:=PPPOE˺MAC}" "${LANG005:=}=${num}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


delete_acct()
{
	num=0
	cmdargs=""

	for acct in `echo ${CGI_accounts} | tr "+" " "`
	do
		cmdargs="${cmdargs} name=${acct}"
		num=$((${num}+1))
	done

	errmsg=`${FLOWEYE} pppoeacct remove ${cmdargs}`

	if [ $? -ne 0 ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		clear_auth_stat ${acct}
		sync_floweye "pppoeacct remove ${cmdargs}"
		WEB_LOGGER "${LANG006:=ɾPPPOE˺}" "${LANG005:=}=${num}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


enable_acct()
{
	num=0
	cmdargs=""

	for acct in `echo ${CGI_accounts} | tr "+" " "`
	do
		cmdargs="${cmdargs} accten=${acct}"
		num=$((${num}+1))
	done

	errmsg=`${FLOWEYE} pppoeacct config ${cmdargs}`

	if [ $? -ne 0 ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else
		sync_floweye "pppoeacct config ${cmdargs}"
		WEB_LOGGER "${LANG007:=PPPOE˺}" "${LANG005:=}=${num}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


disable_acct()
{
	num=0
	cmdargs=""

	for acct in `echo ${CGI_accounts} | tr "+" " "`
	do
		cmdargs="${cmdargs} acctdis=${acct}"
		num=$((${num}+1))
		clear_auth_stat ${acct}
	done
	
	errmsg=`${FLOWEYE} pppoeacct config ${cmdargs}`

	if [ $? -ne 0 ]; then
		retjson 1 "${LANG001:=ʧ}${errmsg}"
	else 
		sync_floweye "pppoeacct config ${cmdargs}"
		WEB_LOGGER "${LANG008:=PPPOE˺}" "${LANG005:=}=${num}"
		retjson 0 "${LANG002:=ɹ}"
	fi
}


clear_auth_stat()
{
	local acct=$1

	# ɾiWAN֤״̬
	for id in `${FLOWEYE} sdwsvr list | awk -v acct=${acct} '{if($4 == acct) print $2}'`
	do
		${FLOWEYE} sdwsvr config entryclose=${id}
	done

	# ɾweb֤״̬
	for ipobj in `${FLOWEYE} ipobj list | grep "/${acct} " | cut -d" " -f1`
	do
		utype=`${FLOWEYE} ipobj get ${ipobj} | grep utype | cut -d"=" -f2`
		${FLOWEYE} ipobj remove ip=${ipobj} uid=${utype}
	done

	# ɾMAC״̬
	for mac in `${FLOWEYE} wamac list | grep " ${acct} " | cut -d" " -f1`
	do
		${FLOWEYE} webauth remove wamac=${mac}
	done
}


edit_acctm()
{
	num=0

	[ "${CGI_poolid}" != "" ] && cmdargs="${cmdargs} poolid=${CGI_poolid}"
	[ "${CGI_maxonline}" != "" ] && cmdargs="${cmdargs} maxonline=${CGI_maxonline}"
	[ "${CGI_expire}" != "" ] && cmdargs="${cmdargs} expire=${CGI_expire}"

	for acct in `echo ${CGI_accounts} | tr "+" " "`
	do
		num=$((${num}+1))
		
		for line in `${FLOWEYE} pppoeacct get name=${acct}`
		do
			export "L_${line}"
		done
		cmdargs="${cmdargs} password=${L_passwd} bindmac=${L_bindmac} bindip=${L_bindip}"
		cmdargs="${cmdargs} outvlan=${L_outvlan} phone=${L_phone} card=${L_card} cname=${L_cname} other=${L_other}"

		errmsg=`${FLOWEYE} pppoeacct set name=${acct} ${cmdargs}`
		[ $? -ne 0 ] && retjson 1 "${num}${errmsg}"
		sync_floweye "pppoeacct set name=${acct} ${cmdargs}"
	done

	WEB_LOGGER "${LANG009:=޸˺}" "${LANG005:=༭}=${num}"
	retjson 0 "${LANG002:=ɹ}"
}


export_account()
{
	account_conf="${PGETC}/account.conf"

	mkdir -p ${WEB_DOWNLOAD}

	if [ "${CGI_type}" = "local" ]; then
		file_name="account.conf"
	else
		file_name="account.csv"
	fi
	
	download_path="${WEB_DOWNLOAD}/${file_name}"

	if [ "${CGI_type}" = "local" ]; then
		if [ "${CGI_pool_id}" != "" ]; then
			grep -E "^g id=${CGI_pool_id}" ${account_conf} > ${download_path}
		else
			grep -E "^g " ${account_conf} > ${download_path}
		fi
	else
		if [ "${PALANG}" = "en" ]; then
			echo "\"GroupID\",\"Group\",\"Account\",\"Password\",\"Birth\",\"Expire\",\"Start\",\"Max_Online\",\"Bind_Mac\",\"Bind_IP\",\"Bind_VLAN\",\"Network_Interface\",\"More\"" > ${download_path}
		else
			echo "\"ûID\",\"û\",\"˺\",\"\",\"ʱ\",\"ʱ\",\"Чʱ\",\"\",\"MAC\",\"IP\",\"vlan\",\"ӿ\",\"Ϣ\"" > ${download_path}
		fi
	fi

	cur_time=`date +%s`
	${FLOWEYE} pppoeacct list poolid=${CGI_pool_id} | grep -i "${CGI_keyword}" | awk \
	-v status="${CGI_status}" -v expire="${CGI_expire}" -v type=${CGI_type} -v cur_time=${cur_time} \
	'{
		#if($17 != "NULL") next; #CITS 2165

		if(status != "" && $11 != status ) next;
		
		if(expire == "expire" && $9 >= 0)
			next;
		else if(expire == "soon") {
			if( $9 > 2592000 || $9 < 0)
			next;
		}

		gsub("%20", " ", $20);

		if($NF == "NULL")
			desc = ";;;;";
		else
			desc = $NF;

		if($13 == "NULL")
			bindmac = "";
		else
			bindmac = $13;
		
		if(type == "local") {
			base = sprintf("u g=%s n=%s p=%s b=%s e=%s s=%s disable=%s maxonline=%s ip=%s mac=%s outvlan=%s outvlan1=%s",
				$1, $3, $4, cur_time, $8, $7, $11, $15, $16, bindmac, $18, $19);

			if($17 != "NULL"){
				result = sprintf("%s outif=%s m=0;%s", base, $17, desc);
			}else{
				result = sprintf("%s m=0;%s", base, desc);
			}

			print result;
		} else {
			print sprintf("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s/%s,%s,%s",
			$1, $2, $3, $4,cur_time, $8, $7, $15, bindmac, $16, $18, $19, $17, desc);
		}
	}' >> ${download_path}

	WEB_LOGGER "${LANG010:=PPPOE˺}"
	retjson 0 "OK" "{\"file_name\":\"${file_name}\"}"
}


query_app()
{
	status="uninstall"
	[ -d "${RAMDISK}/app/adsyn/" ] && status="install"
	
	retjson 0 "${status}"
}


get_account_tree()
{
	dot=""
	acctcnt=0

	printf "["

	if [ "${CGI_pid}" != "0" ]; then
		${FLOWEYE} pppoeacct list pool=${CGI_pid} | awk \
		-v pid=${CGI_pid} \
		'BEGIN{
			dot = "";
			cnt = 0;
		}{
			if($1 != pid) next;

			printf "%s{", dot;
			printf "\"id\":%s", NR;
			printf ",\"account\":\"%s\"", $3;
			printf ",\"more_info\":\"%s\"", $20;
			printf ",\"sort\":2";
			printf "}";
			if(dot == "") dot=",";
			cnt++;
		}END{
			exit cnt;
		}'

		acctcnt=$?
	fi

	[ ${acctcnt} -gt 0 ] && dot=","

	${FLOWEYE} pppoeippool list | sort -nk3 | awk \
	-v pid="${CGI_pid}" -v dot="${dot}" \
	'{
		if($3 != pid) next;

		printf "%s{", dot;
		printf "\"id\":%s", $1;
		printf ",\"account\":\"%s\"", $2;
		printf ",\"more_info\":\"\"";
		printf ",\"isParent\":true";
		printf ",\"children\":[]";
		printf ",\"sort\":1";
		printf "}";
		if(dot == "") dot=",";
	}'

	printf "]"
}


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

	"add_user_account"|"edit_user_account")
		action_check
		add_user_account
		;;

	"addm_user_account")
		action_check
		addm_user_account
		;;

	"unbind_mac")
		action_check
		unbind_mac
		;;
	
	"delete_acct")
		action_check
		delete_acct
		;;

	"enable_acct")
		action_check
		enable_acct
		;;
		
	"disable_acct")
		action_check
		disable_acct
		;;
		
	"edit_acctm")
		action_check
		edit_acctm
		;;

	"export_account")
		action_check
		export_account
		;;
		
	"query_app")
		query_app
		;;

	"get_account_tree")
		retjson 0 "OK" "`get_account_tree`"
		;;

	*)
		retjson 1 "UNKNOW_ACTION"
		;;
esac
