#!/bin/sh
. /lib/functions.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
#

IFNAME_HASH="pptp-$(printf '%s' "${PEERNAME}" | md5sum | cut -c1-8)"

ubus_call_ip() {
	local params="$1"
	local status
	status=$(ubus call ip ip "$params" | jsonfilter -e '@.code')
	if [ "$status" -eq 0 ]; then
		return 0
	fi
	logger -p daemon.notice -t "pptpd" "failed ubus call, status: $status"
	return 1
}

add_routes(){
	local section="$1"
	local remote="$2"
	local gateway
	local target
	local netmask

	config_get gateway "$section" gateway

	[ "$remote" = "$gateway" ] || return

	config_get target "$section" target
	config_get netmask "$section" netmask

	ubus_call_ip "{\"params\":[\"route\", \"add\", \"$target/$netmask\", \"via\", \"$gateway\"]}"
}

ubus_call_ip "{\"params\":[\"link\", \"set\", \"$1\", \"down\"]}"
ubus_call_ip "{\"params\":[\"link\", \"set\", \"$1\", \"name\", \"${IFNAME_HASH}\"]}"
ubus_call_ip "{\"params\":[\"link\", \"set\", \"${IFNAME_HASH}\", \"up\"]}"
[ -n "$LLLOCAL" ] && ubus_call_ip "{\"params\":[\"-6\", \"addr\", \"add\", \"$LLLOCAL\", \"dev\", \"${IFNAME_HASH}\"]}"
[ -n "$LLREMOTE" ] && ubus_call_ip "{\"params\":[\"-6\", \"route\", \"add\", \"$LLREMOTE\", \"dev\", \"${IFNAME_HASH}\"]}"

config_load network
config_foreach add_routes route "$5"

status_file="/var/state/pptp/peer.${PEERNAME}.status"
json_init
json_add_string "conndate" "$(date +%s)"
json_add_string "local_ip" "$4"
json_add_string "remote_ip" "$5"
json_add_string "interface" "${IFNAME_HASH}"
json_dump > "$status_file"
chown pptpd:pptpd "$status_file"
chmod 644 "$status_file"

exit 0
