#!/bin/bash

# Get all open ports on the server

json_file="/usr/local/x-ui/bin/config.json"

IFS=$'\n'

ports=($(jq -r '.inbounds[].port' "$json_file"))

#echo $ports

while true; do
	rules=$(sudo iptables -L INPUT -n --line-numbers)
	connections=$(sudo netstat -tn)
	for port in "${ports[@]}"; do
		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)
			echo "$connectedIPs"
			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
			#limit port only limit port for 40 seconds and again release it nothing more
			has_reject=$(echo "$connectedRules" | grep "REJECT" | sort -r)
			echo "$has_reject"
			#ruleNumbers=$(echo "$connectedRules" | awk '{print $1}' | sort -r)
			#echo "$ruleNumbers"
			if [[ "$ipCount" -gt 1 ]]; then
				echo "should reset"
				if [[ -z "$has_reject" ]]; then
					echo "has reject!"
					sudo iptables -A INPUT -p tcp --dport "$port" -j REJECT --reject-with tcp-reset
				fi
			fi
		fi
	done
	sleep 40
	iptables -F
	sleep 8
done