#!/bin/sh
#
# $FreeBSD$
#
# PROVIDE: generate_rtadvd_conf
# REQUIRE: dhcp6c
# BEFORE: rtadvd
# KEYWORD: shutdown
#

. ${RC_ROUTER_HARNESS}/etc/rc.subr

name='generate_rtadvd_conf'

start_cmd='generate_rtadvd_conf_start'
stop_cmd='generate_rtadvd_conf_stop'
rcvar='generate_rtadvd_conf_enable'

load_rc_config 'generate_rtadvd_conf'

[ -z "$generate_rtadvd_conf_enable" ] && generate_rtadvd_conf_enable='NO'

_prepare_var()
{
	var=$1
	opt=$2

	eval _value=\${${var}}
	eval _${opt}=""
	if [ -n "${_value}" ]
	then
		_text="${opt}=\\\"${_value}\\\""
		eval _${opt}=\"${_text}\"
	fi
}

_prepare_num()
{
	var=$1
	opt=$2

	eval _value=\${${var}}
	eval _${opt}\=""
	if [ -n "${_value}" ]
	then
		_text="${opt}\#${_value}"
		eval _${opt}=\"${_text}\"
	fi
}

_prepare_opt()
{
	var=$1
	opt=$2

	eval _${opt}\=""
	if [ `option_selected ${var}` = "YES" ]
	then
		_text="${opt}"
		eval _${opt}=\"${_text}\"
	fi
}


_build_rtadv()
{
    gen_rtadv_dir=${rc_router_gen_dir}
    rtadvd_conf=${gen_rtadv_dir}/rtadvd.conf
    mkdir -p ${gen_rtadv_dir}

	_search_list=""
	if [ -n "${rtadvd_dns_search_list}" ]
	then
		_search_list=$( echo ${rtadvd_dns_search_list} | sed -e 's/  */,/g' -e 's/^,//' -e 's/,$//' )
	fi

	_prepare_var _search_list dnssl

	_prepare_var rtadvd_pref64_prefix pref64

	_prepare_num rtadvd_mininterval mininterval
	_prepare_num rtadvd_maxinterval maxinterval

	_prepare_num rtadvd_pltime pltime
	_prepare_opt rtadvd_pltimedecr pltimedecr

	_prepare_num rtadvd_vltime vltime
	_prepare_opt rtadvd_vltimedecr vltimedecr

	_prepare_num rtadvd_rltime rltime

    cat ${rc_router_dir}/templates/rtadvd.conf \
        | sed \
            -e "s/@PREF64@/${_pref64}/" \
            -e "s/@MININTERVAL@/${_mininterval}/" \
            -e "s/@MAXINTERVAL@/${_maxinterval}/" \
            -e "s/@PLTIME@/${_pltime}/" \
            -e "s/@PLTIME_DECR@/${_pltimedecr}/" \
            -e "s/@VLTIME@/${_vltime}/" \
            -e "s/@VLTIME_DECR@/${_vltimedecr}/" \
            -e "s/@RLTIME@/${_rltime}/" \
            -e "s/@DNS_SEARCHLIST@/${_dnssl}/" \
            -e "s/@DNS_SERVER@/${rtadvd_dns_server}/" \
        > ${rtadvd_conf}


    echo "" >> ${rtadvd_conf}
    echo "" >> ${rtadvd_conf}

    for interface in ${rtadvd_interfaces}
    do
        echo "${interface}:tc=settings" >> ${rtadvd_conf}
    done
}


generate_rtadvd_conf_start()
{
	_build_rtadv
}

generate_rtadvd_conf_stop()
{
	true
}

################ Epilogue

run_rc_command "$1"

# vim: ft=bash
