#!/bin/sh

_LOGIN_TIME="$(date "+%Y-%m-%d %H:%M:%S")"
CONFIG="luci-app-ipsec-server"
L2TP_PATH=/var/etc/xl2tpd
L2TP_SESSION_PATH=${L2TP_PATH}/session

_USERNAME=${PEERNAME}
_IFACE=${1}
_TTY=${2}
_SPEED=${3}
_LOCALIP=${4}
_PEERIP=${5}

_PID=$(cat /var/run/${_IFACE}.pid 2>/dev/null)
_REMOTEIP=$(cat /var/etc/xl2tpd/xl2tpd.log 2>/dev/null | grep "PID: ${_PID}" | grep -o -E '([0-9]{1,3}[\.]){3}[0-9]{1,3}')

mkdir -p ${L2TP_SESSION_PATH}

cat <<-EOF > ${L2TP_SESSION_PATH}/${_USERNAME}.${_IFACE}
	{
	    "username": "${_USERNAME}",
	    "interface": "${_IFACE}",
	    "tty": "${_TTY}",
	    "speed": "${_SPEED}",
	    "ip": "${_PEERIP}",
	    "remote_ip": "${_REMOTEIP}",
	    "pid": "${_PID}",
	    "login_time": "${_LOGIN_TIME}"
	}
EOF

#只能单用户使用
cfgid=$(uci show ${CONFIG} | grep "@l2tp_users" | grep "\.username='${_USERNAME}'" | cut -d '.' -sf 2)
[ -n "$cfgid" ] && {
	HAS_LOGIN=$(ls ${L2TP_SESSION_PATH} | grep "^${_USERNAME}\.ppp" | grep -v "${_IFACE}")
	[ -n "$HAS_LOGIN" ] && {
		#踢出之前的用户
		KO_IFACE=$(echo $HAS_LOGIN | awk -F '.' '{print $2}')
		KO_PID=$(cat /var/run/${KO_IFACE}.pid 2>/dev/null)
		[ -n "$KO_PID" ] && kill -9 ${KO_PID} >/dev/null 2>&1
		rm -f ${L2TP_SESSION_PATH}/${HAS_LOGIN}
		rm -f /var/run/${KO_IFACE}.pid
	}
	routes=$(uci -q get ${CONFIG}.${cfgid}.routes)
	[ -n "$routes" ] && {
		for router in ${routes}; do
			route add -net ${router} dev ${_IFACE} >/dev/null 2>&1
		done
	}
}

#可根据登录的账号自定义脚本，如组网、日志、限速、权限等特殊待遇。
SCRIPT="/usr/share/xl2tpd/ip-up.d/${_USERNAME}"
[ -s "$SCRIPT" ] && {
	[ ! -x "$SCRIPT" ] && chmod 0755 "$SCRIPT"
	"$SCRIPT" "$@"
}
