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

START=50
USE_PROCD=1

pppoe_triggers() {
    local cfg="$1"
    local interface server_interfaces client_interfaces both_interfaces
    config_get server_interfaces "$cfg" server_interface
    config_get client_interfaces "$cfg" client_interface
    config_get both_interfaces "$cfg" both_interfaces
    for interface in $server_interfaces; do
	append interfaces "$interface" "|"
    done
    for interface in $client_interfaces; do
	append interfaces "$interface" "|"
    done
    for interface in $both_interfaces; do
	append interfaces "$interface" "|"
    done
}

pppoe_relay_instance() {
    local cfg="$1"
    local interface server_interfaces client_interfaces both_interfaces maxsessions timeout OPTIONS
    config_get server_interfaces "$cfg" server_interface
    config_get client_interfaces "$cfg" client_interface
    config_get both_interfaces "$cfg" both_interfaces
    config_get maxsessions "$cfg" maxsessions
    config_get timeout "$cfg" timeout
    config_get_bool use_non_uci_config "$cfg" use_non_uci_config 0

    if [ "$use_non_uci_config" -gt 0 ]; then
	. /etc/default/pppoe-relay
    else
	[ -z "${server_interfaces}${client_interfaces}${both_interfaces}" ] && return 1
	for interface in $server_interfaces; do
	    append OPTIONS "-S $interface"
	done
	for interface in $client_interfaces; do
	    append OPTIONS "-C $interface"
        done
	for interface in $both_interfaces; do
	    append OPTIONS "-B $interface"
	done
	[ -n "$maxsessions" ] && append OPTIONS "-n $maxsessions"
	[ -n "$timeout" ] && append OPTIONS "-i $timeout"
    fi

    procd_open_instance
    procd_set_param command /usr/sbin/pppoe-relay -F
    procd_append_param command $OPTIONS
    procd_close_instance
}

start_service() {
	local use_non_uci_config

	config_load pppoe
	config_foreach pppoe_relay_instance pppoe_relay
}

reload_triggers() {
	local interfaces

	config_load pppoe
	config_foreach pppoe_triggers pppoe_relay

	procd_add_reload_trigger "pppoe"
	procd_add_interface_trigger "$interfaces"
}
