#!/bin/sh /etc/rc.common

START=90
STOP=20

USE_PROCD=1

service_triggers() {
    procd_add_reload_trigger "noddos"
}

reload_service() {
    kill -SIGTERM $(cat /var/lib/noddos/noddos.pid)
}

start_service() {
	# Add multicast route if it does not exist as it is
    # needed for listening to multicast traffic
    netstat -nr | grep '224.0.0' > /dev/null
    if [ "$?" -gt "0" ]; then
        route add -net 224.0.0.0 netmask 224.0.0.0 dev br-lan
    fi

    if [ ! -f /var/lib/noddos/DeviceProfiles.json ]; then
        echo 
        /usr/bin/getnoddosdeviceprofiles
    fi

    # Install cronjob if none exists
    grep getnoddosdeviceprofiles /etc/crontabs/root 2>/dev/null
    if [ "$?" -gt "0" ]; then
        echo "Installing cronjob for noddos"
		# Use awk to generate a random minute
        MINUTE=$(awk -v min=0 -v max=59 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')
        echo "${MINUTE} */3 * * * /usr/bin/getnoddosdeviceprofiles; " 'if [ $? -gt 0 ]; then service noddos reload; fi' >> /etc/crontabs/root
        killall -SIGHUP crond 2>/dev/null
        if [ "$?" -gt "0" ]; then
            /etc/init.d/cron start
        fi
    fi


    lines=$(/usr/sbin/iptables -S | grep -c NODDOS)
    if [ "$lines" -lt "2" ]; then
        echo "Creating iptables chain 'NODDOS'"
        /usr/sbin/iptables --new-chain NODDOS
        /usr/sbin/iptables -t filter --insert FORWARD -j NODDOS
    fi

    lines=$(/usr/sbin/ip6tables -S | grep -c NODDOS)
    if [ "$lines" -lt "2" ]; then
        echo "Creating ip6tables chain 'NODDOS'"
        /usr/sbin/ip6tables --new-chain NODDOS
        /usr/sbin/ip6tables -t filter --insert FORWARD -j NODDOS
    fi

    if [ ! -f "/etc/noddos/noddosapiclient.key" ]; then
        /usr/bin/makenoddoscert.sh
    fi 
    
    if [ ! -f /var/lib/noddos/DeviceDump.json ]; then
        echo "[]" >/var/lib/noddos/DeviceDump.json
    fi

    CONFFILE=/var/etc/noddos.yml
    cp /etc/noddos/noddos.yml-base $CONFFILE

	LANINT=$(uci get network.lan.ifname)
	LANBRIDGE=$(uci get network.lan.type)
	echo 'LanInterfaces:' >> $CONFFILE
	if [ "${LANBRIDGE}" == "bridge" ]; then
		echo "  - br-lan" >> $CONFFILE
    fi
    echo "  - ${LANINT}" >> $CONFFILE
	echo '' >>$CONFFILE

	WANINT=$(uci get network.wan.ifname)
	echo 'WanInterfaces:' >> $CONFFILE
    echo "  - ${WANINT}" >> $CONFFILE
	echo '' >>$CONFFILE


    if [ "$(uci get noddos.@noddos[0].rfc1918)" -eq "1" ]; then
        echo 'ReportTrafficToRfc1918: true' >>$CONFFILE
    else
        echo 'ReportTrafficToRfc1918: false' >>$CONFFILE
    fi
    if [ $(uci get noddos.@noddos[0].upload) -eq "1" ]; then
        echo 'TrafficReportInterval: 3600' >>$CONFFILE
    	echo '' >>$CONFFILE
        echo 'DeviceReportInterval: 14400' >>$CONFFILE
    	echo '' >>$CONFFILE
    else
        echo 'TrafficReportInterval: 0' >>$CONFFILE
    	echo '' >>$CONFFILE
        echo 'DeviceReportInterval: 0' >>$CONFFILE
    	echo '' >>$CONFFILE
    fi

	whitelist=$(uci get noddos.@noddos[0].whitelistipv4 | tr -d "'")
    echo 'WhitelistedIpv4Addresses: ' >> $CONFFILE
    for ipv4 in $whitelist; do
        echo "  - ${ipv4}" >>$CONFFILE
    done
    echo '' >>$CONFFILE

    echo 'WhitelistedIpv6Addresses: ' >> $CONFFILE
    whitelist=$(uci get noddos.@noddos[0].whitelistipv6 | tr -d "'")
    for ipv6 in $whitelist; do
       echo "  - ${ipv6}" >>$CONFFILE
    done
    echo '' >>$CONFFILE

    echo 'WhitelistedMacAddresses: ' >> $CONFFILE
    whitelist=$(uci get noddos.@noddos[0].whitelistmac | tr -d "'")
    for mac in $whitelist; do
        echo " - ${mac}" >>$CONFFILE
    done

    procd_open_instance
    procd_set_param command /usr/sbin/noddos -n -c $CONFFILE

    # respawn automatically if something died, be careful if you have an
    # alternative process supervisor if process dies sooner than
    # respawn_threshold, it is considered crashed and after 5 retries the
    # service is stopped
    procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}

    procd_set_param file /etc/config/noddos
    procd_set_param stdout 0 # forward stdout of the command to logd
    procd_set_param stderr 0 # same for stderr
    procd_set_param user root 
    procd_close_instance
}

stop_service() {
    /usr/sbin/iptables -S | grep NODDOS 2>/dev/null >/dev/null
    if [ "$?" -eq "0" ]; then
        echo "Deleting iptables chain 'NODDOS'"
        /usr/sbin/iptables -t filter --delete FORWARD -j NODDOS
        /usr/sbin/iptables --flush NODDOS
        /usr/sbin/iptables --delete-chain NODDOS
    fi

    /usr/sbin/ip6tables -S | grep NODDOS 2>/dev/null >/dev/null
    if [ "$?" -eq "0" ]; then
        echo "Deleting ip6tables chain 'NODDOS'"
        /usr/sbin/ip6tables -t filter --delete FORWARD -j NODDOS
        /usr/sbin/ip6tables --flush NODDOS
        /usr/sbin/ip6tables --delete-chain NODDOS
    fi

    grep getnoddosdeviceprofiles /etc/crontabs/root 2>/dev/null >/dev/null
    if [ "$?" -eq "0" ]; then
        echo "Deleting cronjob for noddos"
        grep -v getnoddosdeviceprofiles /etc/crontabs/root >/etc/crontabs/root.tmp 2>/dev/null
        mv /etc/crontabs/root.tmp /etc/crontabs/root
        killall -SIGHUP crond 2>/dev/null
    fi
}

savedata_service() {
    kill -SIGUSR1 $(cat /var/lib/noddos/noddos.pid)
}

uploaddata_service() {
    kill -SIGUSR2 $(cat /var/lib/noddos/noddos.pid)
}
