#!/bin/sh
. /usr/share/libubox/jshn.sh
#
# Script which handles the routing issues as necessary for pptpd
#
# When the ppp link comes up, this script is called with the following
# parameters
#       $1      the interface name used by pppd (e.g. ppp3)
#       $2      the tty device name
#       $3      the tty device speed
#       $4      the local IP address for the interface
#       $5      the remote IP address
#       $6      the parameter specified by the 'ipparam' option to pppd
#

service=$(uci -q get "network.${IFNAME#*-}.proto")
[ "$service" != "pptp" ] && exit 0 # Not pptp interface, exit

cl_to_cl=$(uci -q get "network.${IFNAME#*-}.client_to_client")
[ "$cl_to_cl" = "1" ] && [ -n "$IPLOCAL" ] && {
	add_status=$(ubus call ip ip "{\"params\":[\"route\", \"add\", \"${IPLOCAL%.*}.0/24\", \"dev\", \"$IFNAME\"]}" | jsonfilter -e '@.code')
	if [ "$add_status" -eq 0 ]; then
		logger -p daemon.notice -t "pptpd(${IFNAME#*-})" "added route to ${IPLOCAL%.*}.0/24"
	else
		logger -p daemon.notice -t "pptpd(${IFNAME#*-})" "failed to add route to ${IPLOCAL%.*}.0/24"
	fi
}

set_pptp_status() {
	local status_file="/var/state/pptp/"${IFNAME#*-}".status"
	json_init
	json_add_string "conndate" "$(date +%s)"
	json_add_string "local_ip" "$IPLOCAL"
	json_add_string "remote_ip" "$IPREMOTE"
	json_add_string "interface" "${IFNAME}"
	json_dump > "$status_file"
	chown pptpd:pptpd "$status_file"
	chmod 644 "$status_file"
}

if [ -n "$IPLOCAL" ] || [ -n "$IPREMOTE" ]; then
	set_pptp_status
fi

exit 0
