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

START=99
USE_PROCD=1

script=$(readlink "$initscript")
NAME="$(basename ${script:-$initscript})"
config_load "$NAME"

EXTRA_COMMANDS="list_update add_route_interface check_proxy check_nft check_github check_logs check_all check_three"
EXTRA_HELP="        list_update     Updating domain and subnet lists
        add_route_interface  Adding route for interface
        sing_box_config_vless For test vless string
        check_proxy          Check if sing-box proxy works correctly
        check_nft           Show PodkopTable nftables rules
        check_github        Check GitHub connectivity and lists availability
        check_logs         Show podkop logs from system journal
        check_all          Run all checks
        check_three         Run check_proxy, check_nft and check_github"

[ ! -L /usr/sbin/podkop ] && ln -s /etc/init.d/podkop /usr/sbin/podkop

GITHUB_RAW_URL="https://raw.githubusercontent.com/itdoginfo/allow-domains/main"
DOMAINS_RU_INSIDE="${GITHUB_RAW_URL}/Russia/inside-dnsmasq-nfset.lst"
DOMAINS_RU_OUTSIDE="${GITHUB_RAW_URL}/Russia/outside-dnsmasq-nfset.lst" 
DOMAINS_UA="${GITHUB_RAW_URL}/Ukraine/inside-dnsmasq-nfset.lst"
DOMAINS_YOUTUBE="${GITHUB_RAW_URL}/Services/youtube.lst"
SUBNETS_TWITTER="${GITHUB_RAW_URL}/Subnets/IPv4/Twitter.lst"
SUBNETS_META="${GITHUB_RAW_URL}/Subnets/IPv4/Meta.lst"
SUBNETS_DISCORD="${GITHUB_RAW_URL}/Subnets/IPv4/Discord.lst"
SING_BOX_CONFIG="/etc/sing-box/config.json"

config_get update_interval "main" "update_interval" "0 4 * * *"
cron_job="${update_interval} /etc/init.d/podkop list_update"

start_service() {
    log "Start podkop"

    dnsmasqfull
    routing_table_create
    add_mark

    config_get mode "main" "mode"
    case "$mode" in
    "vpn")
        log "VPN mode"
        log "You are using VPN mode, make sure you have installed all the necessary packages, configured, created the zone and forwarding."
        config_get interface "main" "interface" "0"
        if [ -n "$interface" ]; then
            add_route_interface "$interface" "podkop"
        else
            log "Interface undefined"
        fi

        config_get_bool second_enable "second" "second_enable" "0"
        config_get second_mode "second" "second_mode" "0"
        if [ "$second_enable" -eq "1" ] && [ "$second_mode" = "proxy" ]; then
            config_get proxy_config_type "second" "second_proxy_config_type"
            
            if [ "$proxy_config_type" = "outbound" ]; then
                config_get outbound_json "second" "second_outbound_json"
                if [ -n "$outbound_json" ]; then
                    log "Using JSON outbound configuration for second proxy"
                    sing_box_config_outbound_json "$outbound_json" "1603"
                else
                    log "Missing outbound JSON configuration"
                    return
                fi
            else
                config_get proxy_string "second" "second_proxy_string"
                if [[ "$proxy_string" =~ ^ss:// ]]; then
                    sing_box_config_shadowsocks "$proxy_string" "1603"
                elif [[ "$proxy_string" =~ ^vless:// ]]; then
                    sing_box_config_vless "$proxy_string" "1603"
                else
                    log "Unsupported proxy type or missing configuration"
                    return
                fi
            fi
            add_route_tproxy podkop2
            sing_box_config_check
            sing_box_uci
            /etc/init.d/sing-box restart
            /etc/init.d/sing-box enable
        fi

        if [ "$second_enable" -eq "1" ] && [ "$second_mode" = "vpn" ]; then
            log "VPN mode for second"
            config_get interface "second" "second_interface" "0"
            if [ -n "$interface" ]; then
                add_route_interface "$interface" "podkop2"
            else
                log "Interface undefined"
            fi
        fi
        ;;
    "proxy")
        log "Proxy mode"
        if ! command -v sing-box >/dev/null 2>&1; then
            log "Sing-box isn't installed. Proxy mode works with sing-box"
            return
        fi

        # Main - proxy, Second - proxy
        config_get_bool second_enable "second" "second_enable" "0"
        config_get second_mode "second" "second_mode" "0"
        if [ "$second_enable" -eq "1" ] && [ "$second_mode" = "proxy" ]; then
            log "Two proxy enable"
            outbound_main=$(mktemp)
            outbound_second=$(mktemp)

            # Main proxy config
            config_get proxy_config_type main "proxy_config_type"
            if [ "$proxy_config_type" = "outbound" ]; then
                config_get outbound_json main "outbound_json"
                if [ -n "$outbound_json" ]; then
                    echo '{"outbounds":[' > "$outbound_main"
                    echo "$outbound_json" | jq '. + {tag: "main"}' >> "$outbound_main"
                    echo ']}' >> "$outbound_main"
                else
                    log "Missing main outbound JSON configuration"
                    rm -f "$outbound_main" "$outbound_second"
                    return
                fi
            else
                config_get proxy_string main "proxy_string"
                if [[ "$proxy_string" =~ ^ss:// ]]; then
                    sing_box_config_shadowsocks "$proxy_string" "1602"
                    jq '.outbounds[0] + {tag: "main"} | {outbounds: [.]}' $SING_BOX_CONFIG > "$outbound_main"
                elif [[ "$proxy_string" =~ ^vless:// ]]; then
                    sing_box_config_vless "$proxy_string" "1602"
                    jq '.outbounds[0] + {tag: "main"} | {outbounds: [.]}' $SING_BOX_CONFIG > "$outbound_main"
                else
                    log "Unsupported proxy type or missing configuration for main"
                    rm -f "$outbound_main" "$outbound_second"
                    return
                fi
            fi

            # Second proxy config
            config_get proxy_config_type second "second_proxy_config_type"
            if [ "$proxy_config_type" = "outbound" ]; then
                config_get outbound_json second "second_outbound_json"
                if [ -n "$outbound_json" ]; then
                    echo '{"outbounds":[' > "$outbound_second"
                    echo "$outbound_json" | jq '. + {tag: "second"}' >> "$outbound_second"
                    echo ']}' >> "$outbound_second"
                else
                    log "Missing second outbound JSON configuration"
                    rm -f "$outbound_main" "$outbound_second"
                    return
                fi
            else
                config_get proxy_string "second" "second_proxy_string"
                if [[ "$proxy_string" =~ ^ss:// ]]; then
                    sing_box_config_shadowsocks "$proxy_string" "1603"
                    jq '.outbounds[0] + {tag: "second"} | {outbounds: [.]}' $SING_BOX_CONFIG > "$outbound_second"
                elif [[ "$proxy_string" =~ ^vless:// ]]; then
                    sing_box_config_vless "$proxy_string" "1603"
                    jq '.outbounds[0] + {tag: "second"} | {outbounds: [.]}' $SING_BOX_CONFIG > "$outbound_second"
                else
                    log "Unsupported proxy type or missing configuration for second"
                    rm -f "$outbound_main" "$outbound_second"
                    return
                fi
            fi

            jq -s '{
                "log": {"level": "warn"},
                "inbounds": [
                    {
                        "type": "tproxy",
                        "listen": "::",
                        "listen_port": 1602,
                        "sniff": false,
                        "tag": "main"
                    },
                    {
                        "type": "tproxy",
                        "listen": "::",
                        "listen_port": 1603,
                        "sniff": false,
                        "tag": "second"
                    }
                ],
                "outbounds": (.[0].outbounds + .[1].outbounds),
                "route": {
                    "rules": [
                        {
                            "inbound": "main",
                            "outbound": "main"
                        },
                        {
                            "inbound": "second",
                            "outbound": "second"
                        }
                    ],
                    "auto_detect_interface": true
                }
            }' "$outbound_main" "$outbound_second" > $SING_BOX_CONFIG

            rm -f "$outbound_main" "$outbound_second"

            add_route_tproxy podkop
            add_route_tproxy podkop2
        fi

        # Main proxy, second disable/vpn
        config_get_bool second_enable "second" "second_enable" "0"
        config_get second_mode "second" "second_mode" "0"
        if [ "$second_enable" -eq "0" ] || [ "$second_mode" = "vpn" ]; then
            config_get proxy_config_type main "proxy_config_type"
            
            if [ "$proxy_config_type" = "outbound" ]; then
                config_get outbound_json main "outbound_json"
                if [ -n "$outbound_json" ]; then
                    log "Using JSON outbound configuration"
                    sing_box_config_outbound_json "$outbound_json" "1602"
                else
                    log "Missing outbound JSON configuration"
                    return
                fi
            else
                config_get proxy_string main "proxy_string"
                if [[ "$proxy_string" =~ ^ss:// ]]; then
                    sing_box_config_shadowsocks "$proxy_string" "1602"
                elif [[ "$proxy_string" =~ ^vless:// ]]; then
                    sing_box_config_vless "$proxy_string" "1602"
                else
                    log "Unsupported proxy type or missing configuration"
                    return
                fi
            fi
            add_route_tproxy podkop
        fi

        sing_box_config_check
        sing_box_uci
        /etc/init.d/sing-box restart
        /etc/init.d/sing-box enable

        # Main proxy, Second VPN
        config_get_bool second_enable "second" "second_enable" "0"
        config_get second_mode "second" "second_mode" "0"
        if [ "$second_enable" -eq "1" ] && [ "$second_mode" = "vpn" ]; then
            log "VPN mode for seconds"
            log "You are using VPN mode, make sure you have installed all the necessary packages, configured, created the zone and forwarding."
            config_get interface "second" "second_interface" "0"
            if [ -n "$interface" ]; then
                add_route_interface "$interface" "podkop2"
            else
                log "Interface undefined"
            fi
        fi
        ;;
    *)
        log "Requires *vpn* or *proxy* value"
        return
        ;;
    esac

    list_update

    if [ "$domain_list_enabled" -eq 1 ] || [ "$subnets_list_enabled" -eq 1 ]; then
        add_cron_job
    fi

    config_get_bool all_traffic_from_ip_enabled "main" "all_traffic_from_ip_enabled" "0"
    if [ "$all_traffic_from_ip_enabled" -eq 1 ]; then
        log "Adding an IP to redirect all traffic"
        config_list_foreach main all_traffic_ip list_all_traffic_from_ip
    fi

    config_get_bool exclude_from_ip_enabled "main" "exclude_from_ip_enabled" "0"
    if [ "$exclude_from_ip_enabled" -eq 1 ]; then
        log "Adding an IP for exclusion"
        config_list_foreach main exclude_traffic_ip list_exclude_traffic_from_ip
    fi

    config_get_bool yacd "main" "yacd" "0"
    if [ "$yacd" -eq 1 ]; then
        log "Yacd enable"
        jq '.experimental.clash_api = {
            "external_ui": "ui",
            "external_controller": "0.0.0.0:9090"
        }' $SING_BOX_CONFIG >/tmp/sing-box-config-tmp.json && mv /tmp/sing-box-config-tmp.json $SING_BOX_CONFIG
        /etc/init.d/sing-box restart
    fi

    config_get_bool socks5 "main" "socks5" "0"
    if [ "$socks5" -eq 1 ]; then
        log "Socks5 local enable port 2080"
        jq '.inbounds += [{
            "type": "mixed",
            "listen": "0.0.0.0",
            "listen_port": 2080,
            "set_system_proxy": false
        }]' $SING_BOX_CONFIG >/tmp/sing-box-config-tmp.json && mv /tmp/sing-box-config-tmp.json $SING_BOX_CONFIG
        /etc/init.d/sing-box restart
    fi

    config_get_bool exclude_ntp "main" "exclude_ntp" "0"
    if [ "$exclude_ntp" -eq 1 ]; then
        log "NTP traffic exclude for proxy"
        nft insert rule inet PodkopTable mangle udp dport 123 return
    fi
}

stop_service() {
    log "Stopping the podkop"
    rm -f /tmp/dnsmasq.d/podkop*
    remove_cron_job

    log "Flush nft"
    if nft list table inet PodkopTable >/dev/null 2>&1; then
        nft delete table inet PodkopTable
    fi

    log "Flush ip rule"
    if ip rule list | grep -q "podkop"; then
        ip rule del fwmark 0x105 table podkop priority 105
    fi

    if ip rule list | grep -q "podkop2"; then
        ip rule del fwmark 0x106 table podkop2 priority 106
    fi

    log "Flush ip route"
    if ip route list table podkop; then
        ip route flush table podkop
    fi

    if ip route list table podkop2; then
        ip route flush table podkop2
    fi

    log "Stop sing-box"
    config_get mode_main "main" "mode" "0"
    config_get mode_second "second" "second_mode" "0"

    if [ "$mode_main" = "proxy" ] || [ "$mode_second" = "proxy" ]; then
        /etc/init.d/sing-box stop
        /etc/init.d/sing-box disable
    fi
}

restart_service() {
    stop
    start
}

reload_service() {
    stop
    start
}

service_triggers() {
    log "service_triggers start"
    procd_add_config_trigger "config.change" "$NAME" "$initscript" reload 'on_config_change'
}

log() {
    local message="$1"
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    local CYAN="\033[0;36m"
    local GREEN="\033[0;32m"
    local RESET="\033[0m"

    echo -e "${CYAN}[$timestamp]${RESET} ${GREEN}$message${RESET}"
    logger -t "podkop" "$timestamp $message"
}

nolog() {
    local message="$1"
    local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
    local CYAN="\033[0;36m"
    local GREEN="\033[0;32m"
    local RESET="\033[0m"

    echo -e "${CYAN}[$timestamp]${RESET} ${GREEN}$message${RESET}"
}

add_cron_job() {
    remove_cron_job
    crontab -l | {
        cat
        echo "$cron_job"
    } | crontab -
    log "The cron job has been created: $cron_job"
}

remove_cron_job() {
    (crontab -l | grep -v "/etc/init.d/podkop list_update") | crontab -
    log "The cron job removed"
}

list_update() {
    # Main domains processing
    config_get_bool domain_list_enabled "main" "domain_list_enabled" "0"
    if [ "$domain_list_enabled" -eq 1 ]; then
        log "Adding a common domains list"
        add_set "podkop_domains" "main"
        config_get domain_list main "domain_list"
        lists_domains_download "$domain_list"
        dnsmasq_config_check podkop-domains.lst
    fi

    # Main custom domains processing
    config_get custom_domains_list_type "main" "custom_domains_list_enabled" "disabled"
    if [ "$custom_domains_list_type" != "disabled" ]; then
        log "Adding a custom domains list"
        add_set "podkop_domains" "main"
        rm -f /tmp/dnsmasq.d/podkop-custom-domains.lst
        
        if [ "$custom_domains_list_type" = "dynamic" ]; then
            config_list_foreach main custom_domains "list_custom_domains_create" "podkop"
        elif [ "$custom_domains_list_type" = "text" ]; then
            config_get custom_domains_text main "custom_domains_text"
            process_domains_text "$custom_domains_text" "podkop"
        fi
        
        dnsmasq_config_check podkop-custom-domains.lst
    fi

    # Main custom download domains
    config_get_bool custom_download_domains_list_enabled "main" "custom_download_domains_list_enabled" "0"
    if [ "$custom_download_domains_list_enabled" -eq 1 ]; then
        log "Adding a custom domains list from URL"
        add_set "podkop_domains" "main"
        config_list_foreach main custom_download_domains "list_custom_download_domains_create" "podkop"
    fi

    # Main domains delist
    config_get_bool custom_local_domains_list_enabled "main" "custom_local_domains_list_enabled" "0"
    if [ "$custom_local_domains_list_enabled" -eq 1 ]; then
        log "Adding a custom local domain list"
        add_set "podkop_domains" "main"
        config_list_foreach main custom_local_domains "list_custom_local_domains_create" "podkop"
    fi

    config_get_bool delist_domains_enabled "main" "delist_domains_enabled" "0"
    if [ "$delist_domains_enabled" -eq 1 ] && [ "$domain_list_enabled" -eq 1 ]; then
        log "Exclude domains from the common list"
        config_list_foreach main delist_domains "list_delist_domains"
        dnsmasq_config_check podkop-domains.lst
    fi

    # Main subnets processing
    config_get_bool subnets_list_enabled "main" "subnets_list_enabled" "0"
    if [ "$subnets_list_enabled" -eq 1 ]; then
        log "Adding a subnets from list"
        mkdir -p /tmp/podkop
        add_set "podkop_subnets" "main"
        config_list_foreach main subnets "list_subnets_download"
    fi

    # Main custom subnets
    config_get custom_subnets_list_type "main" "custom_subnets_list_enabled" "disabled"
    if [ "$custom_subnets_list_type" != "disabled" ]; then
        log "Adding a custom subnets list"
        add_set "podkop_subnets" "main"
        
        if [ "$custom_subnets_list_type" = "dynamic" ]; then
            config_list_foreach main custom_subnets list_custom_subnets_preprocess "podkop"
        elif [ "$custom_subnets_list_type" = "text" ]; then
            config_get custom_subnets_text main "custom_subnets_text"
            process_subnets_text "$custom_subnets_text" "podkop"
        fi
    fi

    # Main custom download subnets
    config_get_bool custom_download_subnets_list_enabled "main" "custom_download_subnets_list_enabled" "0"
    if [ "$custom_download_subnets_list_enabled" -eq 1 ]; then
        log "Adding a subnets from URL"
        mkdir -p /tmp/podkop
        add_set "podkop_subnets" "main"
        config_list_foreach main custom_download_subnets "list_subnets_download"
    fi

    # Second custom domains processing
    config_get second_custom_domains_list_type "second" "second_custom_domains_list_enabled" "disabled"
    if [ "$second_custom_domains_list_type" != "disabled" ]; then
        log "Adding a custom domains list. Second podkop"
        add_set "podkop2_domains" "second"
        rm -f /tmp/dnsmasq.d/podkop2-custom-domains.lst
        
        if [ "$second_custom_domains_list_type" = "dynamic" ]; then
            config_list_foreach second second_custom_domains "list_custom_domains_create" "podkop2"
        elif [ "$second_custom_domains_list_type" = "text" ]; then
            config_get second_custom_domains_text second "second_custom_domains_text"
            process_domains_text "$second_custom_domains_text" "podkop2"
        fi
        
        dnsmasq_config_check podkop2-custom-domains.lst
    fi

    # Second service domains
    config_get_bool second_domain_service_enabled "second" "second_domain_service_enabled" "0"
    if [ "$second_domain_service_enabled" -eq 1 ]; then
        log "Adding a service for podkop2"
        add_set "podkop2_domains" "second"
        config_get second_service_list second "second_service_list"
        lists_services_download "$second_service_list"
        config_list_foreach second second_custom_domains "list_delist_domains"
        dnsmasq_config_check podkop2-domains.lst
    fi

    # Second custom subnets
    config_get second_custom_subnets_list_type "second" "second_custom_subnets_list_enabled" "disabled"
    if [ "$second_custom_subnets_list_type" != "disabled" ]; then
        log "Adding a custom subnets list. Second"
        add_set "podkop2_subnets" "second"
        
        if [ "$second_custom_subnets_list_type" = "dynamic" ]; then
            config_list_foreach second second_custom_subnets list_custom_subnets_preprocess "podkop2"
        elif [ "$second_custom_subnets_list_type" = "text" ]; then
            config_get second_custom_subnets_text second "second_custom_subnets_text"
            process_subnets_text "$second_custom_subnets_text" "podkop2"
        fi
    fi

    # Restart dnsmasq if needed
    if [ "$domain_list_enabled" -eq 1 ] || [ "$custom_domains_list_type" != "disabled" ] || \
       [ "$custom_download_domains_list_enabled" -eq 1 ] || \
       [ "$second_custom_domains_list_type" != "disabled" ] || \
       [ "$second_domain_service_enabled" -eq 1 ]; then
        /etc/init.d/dnsmasq restart
    fi
}

dnsmasqfull() {
    if /usr/sbin/dnsmasq -v | grep -q "no-nftset"; then
        log "Dnsmasq-full is not installed. Future: link only"
        log "Use script or:"
        log "cd /tmp/ && /bin/opkg download dnsmasq-full && /bin/opkg remove dnsmasq && /bin/opkg install dnsmasq-full --cache /tmp/ && cp /etc/config/dhcp /etc/config/dhcp-old && mv /etc/config/dhcp-opkg /etc/config/dhcp"
        return
    fi
}

routing_table_create() {
    grep -q "105 podkop" /etc/iproute2/rt_tables || echo '105 podkop' >>/etc/iproute2/rt_tables
    config_get_bool second_enable "second" "second_enable" "0"
    if [ "$second_enable" -eq 1 ]; then
        grep -q "106 podkop2" /etc/iproute2/rt_tables || echo '106 podkop2' >>/etc/iproute2/rt_tables
    fi
}

add_set() {
    local set_name="$1"
    local connect="$2"

    nft add table inet PodkopTable
    log "Create set $set_name"
    nft add chain inet PodkopTable mangle { type filter hook prerouting priority -150 \; policy accept \;}
    nft add set inet PodkopTable "$set_name" { type ipv4_addr\; flags interval\; auto-merge\; }
    if [ "$connect" = "main" ]; then
        config_get mode "$connect" "mode"
    else
        config_get mode "$connect" "second_mode"
    fi
    case "$mode" in
    "vpn")
        if ! nft list chain inet PodkopTable mangle | grep -q "ip daddr @"$set_name" meta mark set"; then
            if [ "$connect" = "main" ]; then
                nft add rule inet PodkopTable mangle iifname "br-lan" ip daddr @"$set_name" meta mark set 0x105 counter
            elif [ "$connect" = "second" ]; then
                nft add rule inet PodkopTable mangle iifname "br-lan" ip daddr @"$set_name" meta mark set 0x106 counter
            fi
        fi
        ;;

    "proxy")
        nft add chain inet PodkopTable proxy { type filter hook prerouting priority -100 \; }
        if nft list table inet PodkopTable | grep -q "ip daddr @"$set_name" meta l4proto"; then
            log "Nft rule tproxy exists"
        else
            log "Added nft rule tproxy"
            if [ "$connect" = "main" ]; then
                nft add rule inet PodkopTable mangle iifname "br-lan" ip daddr @"$set_name" meta l4proto tcp meta mark set 0x105 counter
                nft add rule inet PodkopTable mangle iifname "br-lan" ip daddr @"$set_name" meta l4proto udp meta mark set 0x105 counter
                if ! ( nft list table inet PodkopTable | grep -q "meta mark 0x00000105 meta l4proto tcp tproxy" ); then
                    nft add rule inet PodkopTable proxy meta mark 0x105 meta l4proto tcp tproxy ip to :1602 counter
                    nft add rule inet PodkopTable proxy meta mark 0x105 meta l4proto udp tproxy ip to :1602 counter
                fi
            elif [ "$connect" = "second" ]; then
                nft add rule inet PodkopTable mangle iifname "br-lan" ip daddr @"$set_name" meta l4proto tcp meta mark set 0x106 counter
                nft add rule inet PodkopTable mangle iifname "br-lan" ip daddr @"$set_name" meta l4proto udp meta mark set 0x106 counter
                if ! ( nft list table inet PodkopTable | grep -q "meta mark 0x00000106 meta l4proto tcp tproxy" ); then
                    nft add rule inet PodkopTable proxy meta mark 0x106 meta l4proto tcp tproxy ip to :1603 counter
                    nft add rule inet PodkopTable proxy meta mark 0x106 meta l4proto udp tproxy ip to :1603 counter
                fi
            fi
        fi
        ;;

    *)
        log "Requires *vpn* or *proxy* value"
        return
        ;;
    esac
}

add_route_interface() {
    local interface="$1"
    local table="$2"
    local retry_count_route=0
    local max_retries=10

    if ! ip link show "$interface" >/dev/null 2>&1; then
    log "Interface "$interface" undetected, wait 10 sec..."
    sleep 10

        if ! ip link show "$interface" >/dev/null 2>&1; then
            log "Interface "$interface" undetected. exit"
            return
        fi
    fi

    if ! ip link show "$interface" >/dev/null 2>&1; then
        log "Interface "$interface" does not exist, not possible to create a route"
        return
    fi

    if ip route show table $table | grep -q "^default dev"; then
        log "Route for "$interface" exists"
        return 0
    fi

    log "Added route for "$interface""
    while [ $retry_count_route -lt $max_retries ]; do
        if ip route add table $table default dev "$interface" 2>&1 | grep -q "Network is down"; then
            log "Attempt $retry_count_route: Interface "$interface" is down, retrying in 3 seconds..."
            sleep 3
            retry_count_route=$((retry_count_route + 1))
        else
            log "Route for "$interface" added"
            return 0
        fi
    done

    log "The maximum number of attempts has been exceeded. Failed to add a route."
    return
}

add_route_tproxy() {
    local table=$1
    if ! ip route list table $table | grep -q "local default dev lo scope host"; then
        log "Added route for tproxy"
        ip route add local 0.0.0.0/0 dev lo table $table
    else
        log "Route for tproxy exists"
    fi
}

add_mark() {
    if ! ip rule list | grep -q "from all fwmark 0x105 lookup podkop"; then
        log "Create marking rule"
        ip -4 rule add fwmark 0x105 table podkop priority 105
    else
        log "Marking rule exist"
    fi

    config_get_bool second_enable "second" "second_enable" "0"
    if [ "$second_enable" -eq 1 ]; then
        if ! ip rule list | grep -q "from all fwmark 0x106 lookup podkop2"; then
            log "Create marking rule for podkop second"
            ip -4 rule add fwmark 0x106 table podkop2 priority 106
        else
            log "Podkop second marking rule exist"
        fi
    fi
}

lists_domains_download() {
    local URL="$1"

    case "$URL" in
    "ru_inside")
        URL=$DOMAINS_RU_INSIDE
        ;;
    "ru_outside")
        URL=$DOMAINS_RU_OUTSIDE
        ;;
    "ua")
        URL=$DOMAINS_UA
        ;;
    *)
        log "Unidentified list of domains"
        return
        ;;
    esac

    count=0
    while true; do
        if curl -m 3 github.com; then
            wget -q -O /tmp/dnsmasq.d/podkop-domains.lst $URL
            if [ $? -eq 0 ]; then
                sed -i 's/fw4#vpn_domains/PodkopTable#podkop_domains/g' /tmp/dnsmasq.d/podkop-domains.lst
                return 0
            fi
        else
            log "GitHub is not available. Check the internet availability [$count sec]"
            count=$((count + 1))
        fi

        if [ $count -lt 30 ]; then
            sleep_interval=1
        elif [ $count -ge 30 ] && [ $count -lt 60 ]; then
            sleep_interval=5
        elif [ $count -ge 60 ] && [ $count -lt 90 ]; then
            sleep_interval=10
        else
            sleep_interval=30
        fi

        sleep $sleep_interval
    done
}

lists_services_download() {
    local URL="$1"

    case "$URL" in
    "youtube")
        URL=$DOMAINS_YOUTUBE
        ;;
    *)
        log "Unidentified list of domains"
        return
        ;;
    esac

    count=0
    while true; do
        if ping -c 1 -W 3 github.com >/dev/null 2>&1; then
            wget -q -O /tmp/dnsmasq.d/podkop2-domains.lst $URL
            if [ $? -eq 0 ]; then
                delist_downloaded_domains
                sed -i 's/.*/nftset=\/&\/4#inet#PodkopTable#podkop2_domains/g' /tmp/dnsmasq.d/podkop2-domains.lst
                return 0
            fi
        else
            log "GitHub is not available. Check the internet availability [$count sec]"
            count=$((count + 1))
        fi

        if [ $count -lt 30 ]; then
            sleep_interval=1
        elif [ $count -ge 30 ] && [ $count -lt 60 ]; then
            sleep_interval=5
        elif [ $count -ge 60 ] && [ $count -lt 90 ]; then
            sleep_interval=10
        else
            sleep_interval=30
        fi

        sleep $sleep_interval
    done
}

list_subnets_download() {
    local URL="$1"

    case "$URL" in
    "twitter")
        URL=$SUBNETS_TWITTER
        ;;
    "meta")
        URL=$SUBNETS_META
        ;;
    "discord")
        URL=$SUBNETS_DISCORD
        ;;
    *)
        log "Custom URL for subnet"
        if wget -q --spider "$URL"; then
            log "URL is valid"
        else
            log "URL $URL is not valid"
            return
        fi
        ;;
    esac

    local filename=$(basename "$URL")
    mkdir -p /tmp/podkop
    wget -q -O "/tmp/podkop/$filename" "$URL"
    while IFS= read -r subnet; do
        nft add element inet PodkopTable podkop_subnets { $subnet }
    done <"/tmp/podkop/$filename"
}

list_custom_domains_create() {
    local domain="$1"
    local name="$2"
    echo "nftset=/$domain/4#inet#PodkopTable#${name}_domains" >>"/tmp/dnsmasq.d/${name}-custom-domains.lst"
    log "$domain added to the list"
}

list_custom_local_domains_create() {
    local local_file="$1"
    local name="$2"
    local filename=$(basename "$local_file" | cut -d. -f1)
    local config="/tmp/dnsmasq.d/${name}-${filename}.lst"

    rm -f "$config"
    while IFS= read -r domain; do
        echo "nftset=/$domain/4#inet#PodkopTable#${name}_domains" >>$config
    done <"$local_file"
    dnsmasq_config_check ${name}-${filename}.lst
}

list_custom_download_domains_create() {
    local URL="$1"
    local name="$2"
    local filename=$(basename "$URL")
    local config="/tmp/dnsmasq.d/${name}-${filename}.lst"

    rm -f "$config"
    mkdir -p /tmp/podkop
    wget -q -O "/tmp/podkop/${filename}" "$URL"
    while IFS= read -r domain; do
        echo "nftset=/$domain/4#inet#PodkopTable#${name}_domains" >>$config
    done <"/tmp/podkop/$filename"
    dnsmasq_config_check ${name}-${filename}.lst
}

list_custom_subnets_create() {
    local subnet="$1"
    local name="$2"
    nft add element inet PodkopTable ${name}_subnets { $subnet }
}

list_all_traffic_from_ip() {
    local ip="$1"
    if ! nft list chain inet PodkopTable mangle | grep -q "ip saddr $ip"; then
        config_get mode "main" "mode" "0"
        if [ "$mode" = "vpn" ]; then
            nft insert rule inet PodkopTable mangle iifname "br-lan" ip saddr $ip meta mark set 0x105 counter
        elif [ "$mode" = "proxy" ]; then
            nft add set inet PodkopTable localv4 { type ipv4_addr\; flags interval\; }
            nft add element inet PodkopTable localv4 { \
                0.0.0.0/8, \
                10.0.0.0/8, \
                127.0.0.0/8, \
                169.254.0.0/16, \
                172.16.0.0/12, \
                192.0.0.0/24, \
                192.0.2.0/24, \
                192.88.99.0/24, \
                192.168.0.0/16, \
                198.18.0.0/15, \
                198.51.100.0/24, \
                203.0.113.0/24, \
                224.0.0.0/4, \
                240.0.0.0-255.255.255.255 }
            nft insert rule inet PodkopTable mangle iifname "br-lan" ip saddr $ip meta l4proto { tcp, udp } meta mark set 0x105 counter
            nft insert rule inet PodkopTable mangle ip saddr $ip ip daddr @localv4 return
        fi
    fi
}

list_exclude_traffic_from_ip() {
    local ip="$1"
    if ! nft list chain inet PodkopTable mangle | grep -q "ip saddr $ip"; then
        nft insert rule inet PodkopTable mangle ip saddr $ip return
    fi
}

list_delist_domains() {
    local domain="$1"

    if [ -f "/tmp/dnsmasq.d/podkop-domains.lst" ]; then
        sed -i "/$domain/d" /tmp/dnsmasq.d/podkop-domains.lst
        nft flush set inet PodkopTable podkop_domains
        log "Strings containing '$domain' have been excluded from the list"
    else
        log "Config /tmp/dnsmasq.d/podkop-domains.lst not exists"
    fi
}

delist_downloaded_domains() {
    local domains="/tmp/dnsmasq.d/podkop2-domains.lst"

    if [ -f "$domains" ]; then
        while IFS= read -r line; do
            list_delist_domains "$line"
        done <"$domains"
    else
        log "$domains not found"
    fi
}

dnsmasq_config_check() {
    local config="$1"
    if ! /usr/sbin/dnsmasq --conf-file=/tmp/dnsmasq.d/$config --test 2>&1 | grep -q "syntax check OK"; then
        log "Dnsmasq config $config contains errors. Break"
        return
    fi
}

sing_box_config_outbound_json() {
    local json_config="$1"
    local listen_port="$2"
    
    cat > /tmp/base_config.json << EOF
{
  "log": {
    "level": "warn"
  },
  "inbounds": [
    {
      "type": "tproxy",
      "listen": "::",
      "listen_port": $listen_port,
      "sniff": false
    }
  ],
  "outbounds": [],
  "route": {
    "auto_detect_interface": true
  }
}
EOF

    jq --argjson outbound "$json_config" '.outbounds += [$outbound]' /tmp/base_config.json > $SING_BOX_CONFIG
    rm -f /tmp/base_config.json
}

sing_box_uci() {
    local config="/etc/config/sing-box"
    if grep -q "option enabled '0'" "$config" ||
        grep -q "option user 'sing-box'" "$config"; then
        sed -i \
            -e "s/option enabled '0'/option enabled '1'/" \
            -e "s/option user 'sing-box'/option user 'root'/" $config
        log "Change sing-box UCI config"
    else
        log "Sing-box UCI config OK"
    fi
}

sing_box_config_shadowsocks() {
    local STRING="$1"
    local listen_port="$2"

    # Определяем тип SS (2022 или old) по наличию : в base64 части
    if echo "$STRING" | cut -d'/' -f3 | cut -d'@' -f1 | base64 -d 2>/dev/null | grep -q ":"; then
        # Old SS format
        local encrypted_part=$(echo "$STRING" | cut -d'/' -f3 | cut -d'@' -f1 | base64 --decode)
        local method=$(echo "$encrypted_part" | cut -d':' -f1)
        local password=$(echo "$encrypted_part" | cut -d':' -f2-)
    else
        # SS 2022 format
        local method_and_password=$(echo "$STRING" | cut -d'/' -f3 | cut -d'@' -f1)
        local method=$(echo "$method_and_password" | cut -d':' -f1)
        local password=$(echo "$method_and_password" | cut -d':' -f2- | sed 's/%3D/=/g')
        
        # Если method в base64, декодируем
        if echo "$method" | base64 -d &>/dev/null; then
            method=$(echo "$method" | base64 -d)
        fi
    fi

    local server=$(echo "$STRING" | cut -d'@' -f2 | cut -d':' -f1)
    local port=$(echo "$STRING" | sed -n 's|.*:\([0-9]\+\).*|\1|p')

    # Create base config
    cat > /tmp/ss_config.json << EOF
{
  "log": {
    "level": "warn"
  },
  "inbounds": [
    {
      "type": "tproxy",
      "listen": "::",
      "listen_port": $listen_port,
      "sniff": false
    }
  ],
  "outbounds": [
    {
      "type": "shadowsocks",
      "server": "$server",
      "server_port": $port,
      "method": "$method",
      "password": "$password",
      "udp_over_tcp": {
        "enabled": true,
        "version": 2
      }
    }
  ],
  "route": {
    "auto_detect_interface": true
  }
}
EOF

    mv /tmp/ss_config.json $SING_BOX_CONFIG
}

sing_box_config_vless() {
    local STRING="$1"
    local listen_port="$2"

    get_param() {
        local param="$1"
        local value=$(echo "$STRING" | sed -n "s/.*[?&]$param=\([^&?#]*\).*/\1/p")
        value=$(echo "$value" | sed 's/%2F/\//g; s/%2C/,/g; s/%3D/=/g; s/%2B/+/g; s/%20/ /g' | tr -d '\n' | tr -d '\r')
        echo "$value"
    }

    uuid=$(echo "$STRING" | cut -d'/' -f3 | cut -d'@' -f1 | tr -d '\n' | tr -d '\r' | sed 's/False//g')
    server=$(echo "$STRING" | cut -d'@' -f2 | cut -d':' -f1 | tr -d '\n' | tr -d '\r' | sed 's/False//g')
    port=$(echo "$STRING" | cut -d'@' -f2 | cut -d':' -f2 | cut -d'?' -f1 | cut -d'/' -f1 | cut -d'#' -f1 | tr -d '\n' | tr -d '\r' | sed 's/False//g')

    jq -n \
    --arg listen_port "$listen_port" \
    --arg server      "$server" \
    --argjson port    "$port" \
    --arg uuid        "$uuid" \
    --arg type        "$(get_param "type")" \
    --arg flow        "$(get_param "flow")" \
    --arg sni         "$(get_param "sni")" \
    --arg fp          "$(get_param "fp")" \
    --arg security    "$(get_param "security")" \
    --arg pbk         "$(get_param "pbk")" \
    --arg sid         "$(get_param "sid")" \
    --arg alpn        "$(get_param "alpn")" \
    --arg path        "$(get_param "path")" \
    --arg host        "$(get_param "host")" \
    --arg spx         "$(get_param "spx")" \
    --arg insecure    "$(get_param "allowInsecure")" \
    '{
        "log": {
            "level": "warn"
        },
        "inbounds": [
            {
                "type": "tproxy",
                "listen": "::",
                "listen_port": ($listen_port|tonumber),
                "sniff": false
            }
        ],
        "outbounds": [
            {
                "type": "vless",
                "server": $server,
                "server_port": ($port|tonumber),
                "uuid": $uuid,
                "packet_encoding": "",
                "domain_strategy": ""
            }
        ],
        "route": {
            "auto_detect_interface": true
        }
    } |

    if $flow != "" then .outbounds[0].flow = $flow else . end |

    if $type == "ws" then
        .outbounds[0].transport = {
            "type": "ws",
            "path": $path
        } |
        if $host != "" then
            .outbounds[0].transport.headers = {
                "Host": $host
            }
        else . end
    elif $type == "grpc" then
        .outbounds[0].transport = {
            "type": "grpc"
        }
    else . end |

    if $security == "reality" or $security == "tls" then
        .outbounds[0].tls = {
            "enabled": true,
            "server_name": $sni,
            "utls": {
                "enabled": true,
                "fingerprint": $fp
            },
            "insecure": ($insecure == "1")
        } |
        if $alpn != "" then
            .outbounds[0].tls.alpn = ($alpn | split(","))
        else . end |
        if $security == "reality" then
            .outbounds[0].tls.reality = {
                "enabled": true,
                "public_key": $pbk,
                "short_id": $sid
            }
        else . end
    else . end' > $SING_BOX_CONFIG

    if [ $? -eq 0 ]; then
        echo "Config created successfully"
    else
        echo "Error: Invalid JSON config generated"
        return 1
    fi
}

sing_box_config_check() {
    if ! sing-box -c $SING_BOX_CONFIG check >/dev/null 2>&1; then
        log "Sing-box configuration is invalid"
        return
    fi
}

check_proxy() {
    if ! command -v sing-box >/dev/null 2>&1; then
        nolog "sing-box is not installed"
        return 1
    fi

    if [ ! -f $SING_BOX_CONFIG ]; then
        nolog "Configuration file not found"
        return 1
    fi

    nolog "Checking sing-box configuration..."

    if ! sing-box -c $SING_BOX_CONFIG check >/dev/null; then
        nolog "Invalid configuration"
        return 1
    fi

    jq '
        walk(
            if type == "object" then
                with_entries(
                    if [.key] | inside(["uuid", "server", "server_name", "password", "public_key", "short_id"]) then 
                        .value = "MASKED" 
                    else . end
                )
            else . end
        )' $SING_BOX_CONFIG

    nolog "Checking proxy connection..."

    for attempt in `seq 1 5`; do
        response=$(sing-box tools fetch ifconfig.me -D /etc/sing-box 2>/dev/null)
        if ! echo "$response" | grep -q "403 Forbidden"; then
            nolog "Proxy check completed successfully"
            #echo "$response" | sed 's/\([0-9]\+\)\.\([0-9]\+\)\.\([0-9]\+\)\.\([0-9]\+\)/XXX.\2.\3.\4/'
            echo "$response" | sed -n 's/^[0-9]\+\.[0-9]\+\.[0-9]\+\.\([0-9]\+\)$/X.X.X.\1/p'
            return 0
        fi
    done

    nolog "Failed to get a non-403 response after 5 attempts"
    return 1
}

check_nft() {
    if ! command -v nft >/dev/null 2>&1; then
        nolog "nft is not installed"
        return 1
    fi

    nolog "Checking PodkopTable rules..."
    
    # Список всех возможных сетов
    local sets="podkop_domains podkop_subnets podkop2_domains podkop2_subnets localv4"
    
    nolog "Sets statistics:"
    for set_name in $sets; do
        if nft list set inet PodkopTable $set_name >/dev/null 2>&1; then
            local count=$(nft list set inet PodkopTable $set_name 2>/dev/null | grep -c ",")
            nolog "- $set_name: $count elements"
        else
            nolog "- $set_name: not found"
        fi
    done

    # Показываем правила с счетчиками
    nolog "Current chains and rules:"
    nft list table inet PodkopTable | grep "chain\|counter"

    nolog "NFT check completed"
}

check_github() {
    nolog "Checking GitHub connectivity..."
    
    if ! curl -m 3 github.com; then
        nolog "Error: Cannot connect to GitHub"
        return 1
    fi
    nolog "GitHub is accessible"
    
    nolog "Checking lists availability:"
    for url in "$DOMAINS_RU_INSIDE" "$DOMAINS_RU_OUTSIDE" "$DOMAINS_UA" "$DOMAINS_YOUTUBE" \
              "$SUBNETS_TWITTER" "$SUBNETS_META" "$SUBNETS_DISCORD"; do
        local list_name=$(basename "$url")
        wget -q -O /dev/null "$url"
        if [ $? -eq 0 ]; then
            nolog "- $list_name: available"
        else
            nolog "- $list_name: not available"
        fi
    done
}

check_logs() {
    nolog "Showing podkop logs from system journal..."
    
    if command -v logread >/dev/null 2>&1; then
        # Попытка получить последние 50 записей
        logread -e "podkop" | tail -n 50
    else
        nolog "Error: logread command not found"
        return 1
    fi
}

check_three() {
    nolog "\n=== Checking GitHub connectivity ==="
    check_github
    
    nolog "\n=== Checking proxy settings ==="
    check_proxy
    
    nolog "\n=== Checking NFT rules ==="
    check_nft
    
    nolog "\nFull diagnostic check completed"
}

check_all() {
    nolog "Starting full diagnostic check..."
    
    nolog "\n=== Checking recent logs ==="
    check_logs

    check_three
}

process_domains_text() {
    local text="$1"
    local name="$2"
    
    local tmp_file=$(mktemp)
    echo "$text" > "$tmp_file"
    
    sed 's/[, ]\+/\n/g' "$tmp_file" | while IFS= read -r domain; do
        domain=$(echo "$domain" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        if [ -n "$domain" ]; then
            list_custom_domains_create "$domain" "$name"
        fi
    done
    
    rm -f "$tmp_file"
}

process_subnets_text() {
    local text="$1"
    local name="$2"
    
    local tmp_file=$(mktemp)
    echo "$text" > "$tmp_file"
    
    sed 's/[, ]\+/\n/g' "$tmp_file" | while IFS= read -r subnet; do
        subnet=$(echo "$subnet" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
        if [ -n "$subnet" ]; then
            if ! echo "$subnet" | grep -q "/"; then
                subnet="$subnet/32"
            fi
            list_custom_subnets_create "$subnet" "$name"
        fi
    done
    
    rm -f "$tmp_file"
}

list_custom_subnets_preprocess() {
    local subnet="$1"
    local name="$2"
    
    if ! echo "$subnet" | grep -q "/"; then
        subnet="$subnet/32"
    fi
    list_custom_subnets_create "$subnet" "$name"
}