#!/bin/bash
# seeroute2 - Display Xray routing rules with country info
# Dependensi: jq, curl, dig/getent
clear
CONFIG="/var/lib/marzban/xray_config.json"
CACHE_FILE="/tmp/seeroute_cache"

if [[ ! -f "$CONFIG" ]]; then
    echo "Config $CONFIG tidak ditemukan!"
    exit 1
fi

# Warna
GREEN='\033[0;32m'
CYAN='\033[0;36m'
NC='\033[0m'

FILTER="$1"
touch "$CACHE_FILE"

# fungsi resolve domain ke IP
resolve_ip() {
    local host="$1"
    local ip=""
    if [[ "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo "$host"
        return
    fi
    ip=$(dig +short "$host" A 2>/dev/null | head -n1)
    if [[ -z "$ip" ]]; then
        ip=$(getent hosts "$host" | awk '{print $1; exit}')
    fi
    echo "$ip"
}

# fungsi lookup country dengan cache
lookup_country() {
    local ip="$1"
    if [[ -z "$ip" ]]; then
        echo "Unknown"
        return
    fi
    if grep -q "^$ip=" "$CACHE_FILE"; then
        grep "^$ip=" "$CACHE_FILE" | cut -d= -f2
        return
    fi
    local country
    country=$(curl -s "https://ipinfo.io/$ip/country")
    [[ -z "$country" ]] && country="Unknown"
    echo "$ip=$country" >> "$CACHE_FILE"
    echo "$country"
}

printf "${CYAN}%-15s %-12s %-12s${NC}\n" "OutboundTag" "Protocol" "Country"
printf -- "=============================================================\n"

# ambil outbounds (tag, protocol, address/domain)
jq -r '
  .outbounds[] |
  .tag as $tag |
  .protocol as $proto |
  if .settings.servers[0].address then
    [$tag, $proto, .settings.servers[0].address]
  elif .settings.peers[0].endpoint then
    [$tag, $proto, (.settings.peers[0].endpoint | split(":")[0])]
  else
    [$tag, $proto, ""]
  end
  | @tsv
' "$CONFIG" | while IFS=$'\t' read -r tag protocol addr; do

    case "$tag" in
        direct|block|dns-out) continue ;;
    esac

    if [[ -n "$FILTER" && "$tag" != *"$FILTER"* ]]; then
        continue
    fi

    country="-"
    if [[ -n "$addr" ]]; then
        ip=$(resolve_ip "$addr")
        if [[ -n "$ip" ]]; then
            country=$(lookup_country "$ip")
        fi
    fi

    printf "${GREEN}%-15s${NC} %-12s %-12s\n" "$tag" "$protocol" "$country"

    domains=$(jq -r --arg tag "$tag" '.routing.rules[]? | select(.outboundTag == $tag) | .domain[]?' "$CONFIG")
    if [[ -n "$domains" ]]; then
        echo "$domains" | sed 's/^/    -> /'
    else
        echo "    (no domains)"
    fi
    echo
done
