#!/bin/bash 
# Code for service
export RED='\033[0;31m'
export GREEN='\033[0;32m'
export YELLOW='\033[0;33m'
export BLUE='\033[0;34m'
export PURPLE='\033[0;35m'
export CYAN='\033[0;36m'
export CYAN_BG='\033[46;1;97m'   # Latar belakang cyan cerah dengan teks putih
export LIGHT='\033[0;37m'
export PINK='\033[0;35m'
export ORANGE='\033[38;5;208m'
export PINK_BG='\033[45;1;97m'
export BIRU='\033[44;1;97m'
export RED_BG='\033[41;1;97m'   # Latar belakang pink cerah dengan teks putih
export NC='\033[0m'
export INDIGO='\033[38;5;54m'
export TEAL='\033[38;5;30m'
export WHITE='\033[1;37m'

# Mengambil informasi sistem
OS=$(lsb_release -ds)
RAM=$(free -m | awk '/Mem:/ { print $2 }')
UPTIME=$(uptime -p)
IP_VPS=$(hostname -I | awk '{print $1}')
ISP=$(curl -s ipinfo.io/org)
DOMAIN=$(cat /etc/data/domain)

# Mengambil informasi IP lengkap dari ipinfo.io
IP_INFO=$(curl -s "http://ipinfo.io/$IP_VPS/json")
IP_REGION=$(echo "$IP_INFO" | jq -r '.region')
IP_COUNTRY=$(echo "$IP_INFO" | jq -r '.country')
IP_LOC=$(echo "$IP_INFO" | jq -r '.loc')

# Function to print a stylish header
print_header() {
    echo -e " ${TEAL}╭═════════════════════════════════════╮${NC}"
    echo -e " ${TEAL}│${NC}${BIRU}      ❖ INFORMATION ROUTING ❖        ${NC}${TEAL}│${NC}"
    echo -e " ${TEAL}╰═════════════════════════════════════╯${NC}"
    echo ""
}

# Export Banner Status Information
export ERROR="[${RED}ERROR${NC}]";
export INFO="[${YELLOW}INFO${NC}]";
export OKEY="[${GREEN}OKEY${NC}]";
export PENDING="[${YELLOW}PENDING${NC}]";
export SEND="[${YELLOW}SEND${NC}]";
export RECEIVE="[${YELLOW}RECEIVE${NC}]";
ISP=$(curl -s https://ipinfo.io/org | cut -d' ' -f2-)
COUNTRY=$(curl -s https://ipapi.co/json | jq -r .country_name)


# Function to get geoip information using the specified method
get_geoip_info() {
    local address="$1"
    local geoip_info=""

    # Use different methods based on the outbound tag
    if [[ "$2" == *warp* ]]; then
        geoip_info=$(curl -ks4m8 -x socks5://127.0.0.1:40000 -A Mozilla https://ipapi.co/json)
    else
	geoip_info=$(curl -s "https://ipapi.co/$address/json/")
    fi

    echo "$geoip_info"
}

# Mengambil nilai domain, port dan token dari file
domain=$(cat /etc/data/domain)
token=$(cat /etc/data/token.json | jq -r .access_token)
port=$(netstat -tunlp | grep 'python' | awk '{split($4, a, ":"); print a[2]}')

clear
API_URL="https://${domain}/api/core/config"
HEADERS=(-H "accept: application/json" -H "Authorization: Bearer ${token}")

response=$(curl -s -X GET "$API_URL" "${HEADERS[@]}")
routing_rules=$(echo "$response" | jq -r '.routing.rules')
outbounds=$(echo "$response" | jq -r '.outbounds')

if [ ! -z "$routing_rules" ] && [ ! -z "$outbounds" ]; then
    declare -A outbound_ips
    declare -A outbound_protocols

    # Extract and store outbound IPs and Protocols
    for outbound in $(echo "$outbounds" | jq -c '.[]'); do
        tag=$(echo "$outbound" | jq -r '.tag')
        address=$(echo "$outbound" | jq -r '.settings.servers[0].address // .settings.vnext[0].address')
        address=${address:-"N/A"}

        protocol=$(echo "$outbound" | jq -r '.protocol')
        protocol=${protocol:-"N/A"}

        [ ! -z "$address" ] && outbound_ips["$tag"]=$address
        outbound_protocols["$tag"]=$protocol
    done

    # Print table header
    print_header
    echo -e "${LIGHT} ❏ ISP :${NC} ${ORANGE}${ISP}, ${COUNTRY} ${NC}"
    echo -e ""
    printf "%-5s %-17s %-15s %-15s %-25s\n" "No." "OutboundTag" "Protocol" "Country" "Domains"
    echo "----------------------------------------------------------------------------"

    # Variable to keep track of seen domains
    seen_domains=()

    count=1

    for rule in $(echo "$routing_rules" | jq -c '.[]'); do
        outbound_tag=$(echo "$rule" | jq -r '.outboundTag // ""')
        protocol=${outbound_protocols["$outbound_tag"]}
        protocol=${protocol:-"N/A"}

        address=${outbound_ips["$outbound_tag"]}
        domains=$(echo "$rule" | jq -r '.domain // [""] | @sh' | sed "s/'//g" | sed "s/\[//g" | sed "s/\]//g" | sed "s/ext:geositeindo.dat://g" | sed "s/domain://g")

        # Fetch IP info only if address is not N/A
        if [ "$address" != "N/A" ]; then
            geoip_info=$(get_geoip_info "$address" "$outbound_tag")
            ip_info=$(echo "$geoip_info" | jq -r '.country_name // "N/A"')
        else
            ip_info="N/A"
        fi

        # Remove 'geosite:' from domains and filter duplicates
        cleaned_domains=()
        IFS=' ' read -ra domain_array <<< "$domains"
        for domain in "${domain_array[@]}"; do
            cleaned_domain=$(echo "$domain" | sed -E 's/\..*//; s/geosite://g; s/full:.*//; s/regexp:.*//; /^[[:space:]]*$/d')
            if [[ ! " ${seen_domains[@]} " =~ " $cleaned_domain " ]]; then
                seen_domains+=("$cleaned_domain")
                cleaned_domains+=("$cleaned_domain")
            fi
        done

        # Set colors
        color_reset="\e[0m"
        color_red="\e[91m"
        color_yellow="\e[93m"
        color_blue="\e[94m"

        # Color the Country column
        color_code=$color_reset  # Reset color
        if [ "$ip_info" != "N/A" ]; then
            color_code="\e[32m"  # Green color for non-N/A countries
        else
            color_code=$color_red  # Red color for N/A countries
        fi

        # Ambil kata dari domain sesuai aturan
        final_domains=()
        for domain in "${cleaned_domains[@]}"; do
        num_dots=$(grep -o '\.' <<< "$domain" | wc -l)
        if [ "$num_dots" -eq 1 ]; then
        final_domains+=("$(echo "$domain" | cut -d':' -f2)")
        elif [ "$num_dots" -eq 2 ]; then
        final_domains+=("$(echo "$domain" | cut -d'.' -f2- | cut -d':' -f2)")
        else
        final_domains+=("$domain")
        fi
    done

        # Hapus duplikasi dari cleaned_domains
        final_domains=($(echo "${cleaned_domains[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

        # Print formatted output
        for domain in "${final_domains[@]}"; do
        printf "%-5s %-18s %-15s $color_code%-15s\e[0m %-25s\n" "$count" "$outbound_tag" "$protocol" "$ip_info" "$count. $domain"
        count=$((count+1))
        done
    done
else
    echo "Failed to fetch routing rules and outbounds from API."
fi
echo "----------------------------------------------------------------------------"
