#!/usr/bin/env bash
set -euo pipefail

# ========================
#  CONFIGURABLE VARIABLES
# ========================
URL="http://45.88.0.109/newdeny3.txt"

# ========================
#  CREATE TEMP FILE
# ========================
TMPDIR=$(mktemp -d)
TMPFILE="$TMPDIR/newdeny3.txt"

# 1) Download the list with wget
if ! wget -qO "$TMPFILE" "$URL"; then
  echo "Error: Failed to download $URL" >&2
  exit 1
fi

# ========================
#  1) Process Xtream-UI configuration
# ========================
XTREAM_CONF="/home/xtreamcodes/iptv_xtream_codes/nginx/conf/nginx.conf"
if [ -f "$XTREAM_CONF" ]; then
    chattr -ia "$XTREAM_CONF"
    awk 'FNR==NR { buf[++n] = $0; next }
         /^.*rewrite_log on;.*$/ {
           for (i = 1; i <= n; i++) print buf[i]
           print
           next
         }
         { print }' "$TMPFILE" "$XTREAM_CONF" > "$XTREAM_CONF.tmp"
    mv "$XTREAM_CONF.tmp" "$XTREAM_CONF"
    chattr +ia "$XTREAM_CONF"
    /home/xtreamcodes/iptv_xtream_codes/start_services.sh
    echo "? Xtream-UI config updated and services restarted."
    exit 0
fi

# ========================
#  2) Process streamcreed configuration
# ========================
XTREAM_CONF="/home/streamcreed/nginx/conf/nginx.conf"
if [ -f "$XTREAM_CONF" ]; then
    chattr -ia "$XTREAM_CONF"
    awk 'FNR==NR { buf[++n] = $0; next }
         /^.*rewrite_log on;.*$/ {
           for (i = 1; i <= n; i++) print buf[i]
           print
           next
         }
         { print }' "$TMPFILE" "$XTREAM_CONF" > "$XTREAM_CONF.tmp"
    mv "$XTREAM_CONF.tmp" "$XTREAM_CONF"
    chattr +ia "$XTREAM_CONF"
    /home/streamcreed/start_services.sh
    echo "? streamcreed config updated and services restarted."
    exit 0
fi

# ========================
#  2) Process OneStream configuration
# ========================
XTREAM_CONF="/etc/nginx/nginx.conf"
if [ -f "$XTREAM_CONF" ]; then
    chattr -ia "$XTREAM_CONF"
    awk 'FNR==NR { buf[++n] = $0; next }
         /^.*rewrite_log on;.*$/ {
           for (i = 1; i <= n; i++) print buf[i]
           print
           next
         }
         { print }' "$TMPFILE" "$XTREAM_CONF" > "$XTREAM_CONF.tmp"
    mv "$XTREAM_CONF.tmp" "$XTREAM_CONF"
    chattr +ia "$XTREAM_CONF"
    service nginx restart
    echo "? OneStream config updated and services restarted."
    exit 0
fi

# ========================
#  3) Process XUI.ONE configuration
# ========================
XUI_CONF="/home/xui/bin/nginx/conf/nginx.conf"
if [ -f "$XUI_CONF" ]; then
    chattr -ia "$XUI_CONF"
    awk 'FNR==NR { buf[++n] = $0; next }
         /^.*rewrite_log on;.*$/ {
           for (i = 1; i <= n; i++) print buf[i]
           print
           next
         }
         { print }' "$TMPFILE" "$XUI_CONF" > "$XUI_CONF.tmp"
    mv "$XUI_CONF.tmp" "$XUI_CONF"
    chattr +ia "$XUI_CONF"
    /home/xui/service stop && /home/xui/service start
    echo "? XUI.ONE config updated and service restarted."
    exit 0
fi

# ========================
#  4) Special Process NXT configuration
# ========================
NXT_CONF="/home/nxt/bin/nginx/conf/block.conf"
if [ -f "$NXT_CONF" ]; then
    chattr -ia "$NXT_CONF"
    # Clear existing content and copy the new list directly
    cat "$TMPFILE" > "$NXT_CONF"
    chattr +ia "$NXT_CONF"
    # Restart NXT nginx
    cd /home/nxt/bin/nginx/sbin && pkill nginx && ./nginx
    echo "? NXT block.conf replaced and nginx restarted."
    exit 0
fi

# ========================
#  5) Fallback: apply bans via iptables/ip6tables
# ========================
echo "? No supported configuration found. Applying ban rules..."

IPV4_RULES=()
IPV6_RULES=()

while IFS= read -r ENTRY; do
    [[ -z "$ENTRY" ]] && continue
    [[ "$ENTRY" =~ ^# ]] && continue

    CLEAN=$(echo "$ENTRY" | tr -d '[:space:];\r')
    CLEAN=${CLEAN#deny}

    if [[ "$CLEAN" != */* ]]; then
        CLEAN="$CLEAN/32"
    fi

    if [[ "$CLEAN" == *:* && "$CLEAN" != *.* ]]; then
        IPV6_RULES+=("$CLEAN")
        echo "  - Blocking IPv6: $CLEAN"
        ip6tables -I INPUT -s "$CLEAN" -j DROP ||             echo "Warning: Failed to apply IPv6 rule $CLEAN" >&2
    else
        IPV4_RULES+=("$CLEAN")
        echo "  - Blocking IPv4: $CLEAN"
        iptables -I INPUT -s "$CLEAN" -j DROP ||             echo "Warning: Failed to apply IPv4 rule $CLEAN" >&2
    fi
done < "$TMPFILE"

# ========================
#  6) Install iptables-persistent if missing (Ubuntu)
# ========================
if ! dpkg -s iptables-persistent >/dev/null 2>&1; then
    echo "Info: 'iptables-persistent' not found. Installing..."
    apt-get update &&     DEBIAN_FRONTEND=noninteractive apt-get install -y iptables-persistent ||         echo "Warning: Failed to install iptables-persistent" >&2
fi

SAVE_DIR="/etc/iptables"
if [ ! -d "$SAVE_DIR" ]; then
    mkdir -p "$SAVE_DIR" || {
        echo "Error: Could not create $SAVE_DIR. Run with sudo." >&2
        exit 1
    }
fi

# ========================
#  7) Save persistent rules
# ========================
SAVE4="$SAVE_DIR/rules.v4"
SAVE6="$SAVE_DIR/rules.v6"

if [ ${#IPV4_RULES[@]} -gt 0 ]; then
    iptables-save > "$SAVE4" && echo "? IPv4 rules saved to $SAVE4" ||         echo "Warning: Failed to save IPv4 rules to $SAVE4" >&2
fi

if [ ${#IPV6_RULES[@]} -gt 0 ]; then
    ip6tables-save > "$SAVE6" && echo "? IPv6 rules saved to $SAVE6" ||         echo "Warning: Failed to save IPv6 rules to $SAVE6" >&2
fi

if [ ${#IPV4_RULES[@]} -eq 0 ] && [ ${#IPV6_RULES[@]} -eq 0 ]; then
    echo "Notice: No ban entries were applied."
fi
