#!/bin/bash

# Get all open ports on the server

json_file="/usr/local/x-ui/bin/config.json"

IFS=$'\n'

if [ -z "$(command -v jq)" ]; then
    apt install jq -y
fi

ports=($(jq -r '.inbounds[].port' "$json_file"))

rules=$(sudo iptables -L INPUT -n --line-numbers)
connections=$(sudo netstat -tn)
line=1
for port in "${ports[@]}"; do
        ((line++))
        if [[ ! -z "$port" ]] && [[ "$port" -ge 10000 ]]; then
            # Get connected IPs on the specific port
            connectedRules=$(echo "$rules" | grep ":$port")
            connectedIPs=$(echo "$connections" | grep ":$port" | awk '{print $5}' | cut -d: -f1 | sort | uniq)
            whitelistedIP=""
            ipCount=0

            IFS=$'\n'
            for ip in $(echo "$connectedIPs"); do
                    ip=$(echo "$ip" | tr -d '[:space:]')
                    if [[ ! -z "$ip" ]]; then
                            ((ipCount++))
                            if [[ "$ipCount" -eq 1 ]]; then
                                    whitelistedIP=$ip
                            fi
                    fi
            done
            whited=$(echo "$connectedRules" | grep "$whitelistedIP.*:$port" | sort -r)
            has_reject=$(echo "$connectedRules" | grep "REJECT.*:$port" | sort -r)
            ruleNumbers=$(echo "$connectedRules" | awk '{print $1}' | sort -r)
            if [[ "$ipCount" -gt 1 ]]; then
                echo "${line}- ${port} (${ipCount})"
            fi
        fi
done
