#!/bin/bash

#
# Copyright (C) 2024 Nosignal <https://github.com/nosignals>
# 
# Contributors:
# - bobbyunknown <https://github.com/bobbyunknown>
#
# https://opensource.org/license/mit
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

neko_status=$(uci -q get neko.cfg.enabled)
neko_new_interface=$(uci -q get neko.cfg.new_interface)
neko_delay=$(uci -q get neko.cfg.delay)
neko_dir="/etc/neko"
tun_bin="$neko_dir/core/tun"
neko_pid="$neko_dir/tmp/neko_pid.txt"
log="$neko_dir/tmp/log.txt"
firewall="/etc/init.d/firewall"
neko_version=$1

neko_checknewver(){
    new_version=$(curl -m 5 -f -s https://raw.githubusercontent.com/nosignals/openwrt-neko/main/luci-app-neko/Makefile | grep PKG_VERSION: | cut -d= -f2)
    if [ $neko_version == $new_version ] || [ -z $new_version ]; then
        strversion="- Latest"
    else
        strversion="- New v.$new_version"
        if [ $1 == "log" ]; then
            echo "[ `date +%T` ] New Version detected. v.$new_version" >> $log
            echo "[ `date +%T` ] New Version detected. v.$new_version"
        fi
    fi
}

neko_reload(){
    echo "Checking New Interfaces."
    dt=`ubus call network.interface dump`
    len=`echo $dt | jq '.interface' | jq length`

    for (( i=0; i<$len; i++ ))
    do
        tmpdt=`echo $dt | jq ".interface[$i]"`
        status=`echo $tmpdt | jq '.up'`
        if [ $status = true ]; then
            iface=`echo $tmpdt | jq '.interface' | sed 's/"//g'`
            uptime=`echo $tmpdt | jq '.uptime'`
            if [ "$iface" == "loopback" -o "$iface" == "lan" ]; then
                echo "Interfaces $iface is whitlisted"
            else
                if [[ ! -d "/tmp/iface" ]]; then
                    echo "creating tmp dir"
                    mkdir /tmp/iface
                fi
        
                if [ ! -e /tmp/iface/$iface ]; then
                    echo $uptime > /tmp/iface/$iface
                    $firewall restart
                    echo "[ `date +%T` ] - Detected interfaces $iface changed, Reloading Firewall " >> $log
                    $tun_bin -ks
                    uptime_now=`cat /proc/uptime | cut -d. -f1`
                    if [ "$uptime_now" -lt 60 ]; then
                        service neko restart
                    fi
                fi

                last_uptime=`cat /tmp/iface/$iface`
                echo $uptime > /tmp/iface/$iface
                echo "- $iface Uptime $uptime s, last Uptime $last_uptime s"

                if (( $uptime < $last_uptime )) || [ -z $last_uptime ]; then
                    echo "reloading firewall"
                    $firewall restart
                    echo "[ `date +%T` ] - Detected interfaces $iface changed, Reloading Firewall " >> $log
                    sleep 1
                    $tun_bin -ks
                else
                    echo "nothing"
                fi
            fi
        fi
    done
}

if [ "$neko_status" == 1 ] && [ "$neko_new_interface" == 1 ]; then
    echo "[ `date +%T` ] - Auto Restart Firewall : ON " >> $log
    cnt=0;
    while true
    do
        ((cnt++))
        sleep "$neko_delay"
        neko_reload
        if [ $cnt == 30 ]; then
            neko_checknewver "log"
        fi
    done
else
    echo "[ `date +%T` ] - Auto Restart Firewall : OFF " >> $log
    sleep 20 && neko_checknewver "log"
fi