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

START=50
USE_PROCD=1

pppoe_triggers() {
	local cfg="$1"
	local interface
	config_get interface "$cfg" interface
}

pppoe_instance() {
	local cfg="$1"
	local interface ac_name service_names service_name maxsessionsperpeer localip firstremoteip maxsessions optionsfiles randomsession unit offset timeout mss sync OPTIONS
	config_get interface "$cfg" interface
	config_get ac_name "$cfg" ac_name
	config_get service_names "$cfg" service_name
	config_get maxsessionsperpeer "$cfg" maxsessionsperpeer
	config_get localip "$cfg" localip
	config_get firstremoteip "$cfg" firstremoteip
	config_get maxsessions "$cfg" maxsessions
	config_get optionsfile "$cfg" optionsfile
	config_get_bool randomsession "$cfg" randomsession 1
	config_get_bool unit "$cfg" unit 0
	config_get offset "$cfg" offset
	config_get timeout "$cfg" timeout
	config_get mss "$cfg" mss
	config_get_bool sync "$cfg" sync 0
	config_get use_non_uci_config "$cfg" use_non_uci_config 0

	if [ "$use_non_uci_config" -gt 0 ]; then
	    . /etc/default/pppoe-server
        else
	    [ -z "$interface" ] && return 1
	    [ -n "$ac_name" ] && append OPTIONS "-C $ac_name"
	    for service_name in $service_names; do
		append OPTIONS "-S $service_name"
	    done
	    append OPTIONS "-I $interface"
	    [ -n "$maxsessionsperpeer" ] && append OPTIONS "-x $maxsessionsperpeer"
	    [ -n "$localip" ] && append OPTIONS "-L $localip"
	    [ -n "$firstremoteip" ] && append OPTIONS "-R $firstremoteip"
	    [ -n "maxsessions" ] && append OPTIONS "-N $maxsessions"
	    [ -n "optionsfile" ] && append OPTIONS "-O $optionsfile"
	    [ "$randomsession" = "1" ] && append OPTIONS "-r"
	    [ "$unit" = "1" ] && append OPTIONS "-u"
	    [ -n "$offset" ] && append OPTIONS "-o $offset"
	    [ -n "$timeout" ] && append OPTIONS "-T $timeout"
	    [ -n "$mss" ] && append OPTIONS "-m $mss"
	    [ "$sync" = "1" ] && append OPTIONS "-s"
	fi

	procd_open_instance
	procd_set_param command /usr/sbin/pppoe-server -F
	procd_append_param command $OPTIONS
	procd_set_param file /etc/ppp/options
	procd_append_param file /etc/ppp/pppoe-server-options
	procd_close_instance
}

start_service() {
	config_load pppoe
	config_foreach pppoe_instance pppoe_server
}

service_triggers() {
	local interface
	config_load pppoe
	config_foreach pppoe_triggers pppoe_server

	procd_add_reload_trigger "pppoe"
	procd_add_interface_trigger "$interface"
}
