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

START=50
STOP=50
USE_PROCD=1

pppoe_triggers() {
    local cfg="$1"
    local enabled interface
    config_get_bool enabled "$cfg" enabled 1
    [ "$enabled" -gt 0 ] || return 0
    config_get interface "$cfg" interface
    procd_add_reload_interface_trigger $interface
}

pppoe_instance() {
    local cfg="$1"
    local enabled interface device ac_name service_names service_name maxsessionsperpeer localip firstremoteip maxsessions optionsfiles randomsession unit offset timeout mss sync OPTIONS
    config_get_bool enabled "$cfg" enabled 1
    [ "$enabled" -gt 0 ] || return 0
    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_bool use_non_uci_config "$cfg" use_non_uci_config 0

    if [ "$use_non_uci_config" -gt 0 ]; then
	. /etc/default/pppoe-server
    else
	. /lib/functions/network.sh
	network_get_physdev device $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 $device"
	[ -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 -k $OPTIONS
    procd_set_param respawn
    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() {
    procd_add_reload_trigger "pppoe"

    config_load pppoe
    config_foreach pppoe_triggers pppoe_server
}
