#!/bin/bash
#
# Copyright (C) 2024 nosignal

arch=`uname -m`
neko_dir="/etc/neko"
tmp_dir="/tmp"

echo "[ `date +%T` ] - Checking Files..."

files_check() {
    if [ -n "$(command -v nginx)" ];then
cat << 'EOF' > /etc/nginx/conf.d/nekoclash.locations
location /nekoclash {
    alias /www/nekoclash;
    index index.php index.html index.htm;

    location ~ \.php$ {
        if (!-f $request_filename) {
            return 404;
        }
        fastcgi_pass unix:/var/run/php8-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
    }
}
EOF
        /etc/init.d/nginx restart
    elif [ -n "$(command -v lighttpd)" ];then
cat << 'EOF' > /etc/lighttpd/conf.d/81-php.conf
cgi.assign += ( ".php" => "/usr/bin/php-cgi" )
EOF
        /etc/init.d/lighttpd restart
    else
        uci set uhttpd.main.index_page='index.php'
        uci set uhttpd.main.interpreter='.php=/usr/bin/php-cgi'
        uci commit uhttpd

        /etc/init.d/uhttpd restart
    fi
}
if [ -f "/tmp/neko/neko.bak" ]; then
    echo "[ `date +%T` ] - Old Configs"
    echo "[ `date +%T` ] - Restoring..."
    
    if [ -f "/tmp/neko/cache.db" ]; then
        cp -rf "/tmp/neko/cache.db" "/etc/neko/cache.db"
    fi
    cp -rf /tmp/neko/config/* "/etc/neko/config/"
    cp -rf /tmp/neko/proxy_provider/* "/etc/neko/proxy_provider/"
    cp -rf /tmp/neko/rule_provider/* "/etc/neko/rule_provider/"
else
    echo "[ `date +%T` ] - Old Files Not Detected, Checking Files"
    files_check
fi

uci set neko.cfg.enabled='0'
uci commit neko
