#!/bin/sh

rtadvd=/usr/sbin/radvd
rtadvdconfigfile=/etc/tsp/tsprtadvd.conf
ifconfig=/sbin/ifconfig
sysctl=/sbin/sysctl
LAN_ADDR=$(uci get ipv6.lan.global_addr)
LAN_IF=$(uci get ipv6.lan.ifname)
LAN_PREFIX=$(uci get ipv6.lan.prefix)
LAN_PREFIX_LEN=$(uci get ipv6.lan.prefix_len)
ADV_TIME=$(uci get ipv6.lan_radvd.adv_time)

if [ $LAN_IF ]; then
    ifconfig $LAN_IF down
    ifconfig $LAN_IF up
else
	echo "Interface not set"
	exit 1
fi

$sysctl -w net.ipv6.conf.all.forwarding=1 # ipv6_forwarding enabled
$ifconfig $LAN_IF add $LAN_ADDR/$LAN_PREFIX_LEN
# Router advertisement configuration 
echo "Create new $rtadvdconfigfile"
echo "##### rtadvd.conf made by TSP ####" > "$rtadvdconfigfile"
echo "interface $LAN_IF" >> "$rtadvdconfigfile"
echo "{" >> "$rtadvdconfigfile"
echo " AdvSendAdvert on;" >> "$rtadvdconfigfile"
if [ $ADV_TIME ]; then
    echo " AdvDefaultLifetime $ADV_TIME;" >> "$rtadvdconfigfile"
else
	echo "Do not set ADV lifetime"
fi
echo " prefix $LAN_PREFIX:/64" >> "$rtadvdconfigfile"
echo " {" >> "$rtadvdconfigfile"
echo " AdvOnLink on;" >> "$rtadvdconfigfile"
echo " AdvAutonomous on;" >> "$rtadvdconfigfile"
echo " };" >> "$rtadvdconfigfile"
echo "};" >> "$rtadvdconfigfile"
echo "" >> "$rtadvdconfigfile"

   if [ -f $rtadvdconfigfile ]; then
      $rtadvd -C $rtadvdconfigfile -m stderr_syslog -p /var/run/radvd.pid
      echo "Starting radvd: $rtadvd -C $rtadvdconfigfile -m stderr_syslog -p /var/run/radvd.pid"
   else
      echo "Error : file $rtadvdconfigfile not found"
      exit 1
   fi
