#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2015 OpenWrt.org

START=60
USE_PROCD=1

BIN=xl2tpd
RUN_D="/var/run/xl2tpd"
PID_F="/var/run/xl2tpd.pid"
CONF_F="$RUN_D/xl2tpd.conf"
SECRETS_F="$RUN_D/xl2tp-secrets"
# Flag to use legacy config files rather than UCI-generated ones
USE_LEGACY_CONFIG=0

XL2TP_BOOLS='
ipsec_saref
access_control
debug_avp
debug_network
debug_packet
debug_state
debug_tunnel
exclusive
assign_ip
hidden_bit
length_bit
refuse_chap
require_chap
refuse_pap
require_pap
refuse_authentication
require_authentication
unix_authentication
ppp_debug
flow_bits
challenge
autodial
redial
'

config_cb() {
	config_type="$1"
	config_name="$2"

	# ignore empty type
	[ -z "$config_type" ] && return 0

	# ignore 'secret' sections
	[ "$config_type" = "secret" ] && return 0

	echo -e "\n[$config_type]" >> "$CONF_F"
}

option_cb() {
	option_name="$1"
	option_value="$2"

	# ignore 'secret' sections
	[ "$config_type" = "secret" ] && return 0

	[ "$config_type" = "global" ] && [ "$option_name" = "use_legacy_config" ] && {
		[ "$option_value" = 1 ] && USE_LEGACY_CONFIG=1
		return 0
	}

	for p in $XL2TP_BOOLS; do
		[ "$p" = "$option_name" ] && {
			if [ "$option_value" = 1 ]; then
				option_value="yes"
			else
				option_value="no"
			fi
		}
	done

	echo "${option_name//_/ } = $option_value" >> "$CONF_F"
}

secrets_add() {
	local cfg="$1"

	config_get local "$cfg" local
	config_get remote "$cfg" remote
	config_get secret "$cfg" secret

	echo "$local $remote $secret" >> "$SECRETS_F"
}

reload_service() {
	restart
}

service_triggers() {
	procd_add_reload_trigger xl2tp
}

start_service() {
	rm -rf "$RUN_D"
	mkdir -p "$RUN_D"

	config_load xl2tp
	config_foreach secrets_add secret

	[ "$USE_LEGACY_CONFIG" = 1 ] && {
		# set paths to legacy config files for backward compatibility
		CONF_F="/etc/xl2tpd/xl2tpd.conf"
		SECRETS_F="/etc/xl2tpd/xl2tp-secrets"
	}

	procd_open_instance
	procd_set_param command $BIN -D -l -p "$PID_F" -c "$CONF_F" -s "$SECRETS_F"
	procd_set_param respawn
	procd_close_instance
}

stop_service() {
	rm -rf "$RUN_D"
	rm -rf "$PID_F"
}
