import os
import sys
import subprocess
import atexit
from threading import Timer
import string
import random
import signal
import socket
import codecs
import datetime
import time

if __name__ == '__main__':
    local_ip = "127.0.0.1"
    local_port = 12345 #add some other port here.
    udp_external_ip = "some IP here"
    buffer_size = 4096 #potentially not large enough?
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock_external = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("127.0.0.1", local_port))
    print('reached deadlock')
    try:
        while True:
            data, addr = sock.recvfrom(buffer_size)
            data = codecs.decode(data, "utf-8", "ignore")
            ip = addr[0]
            port = addr[1]
            #print('port: ', port, " ip: ", ip)
            #print(data)
            # update 17th february 2024: updating the kernel made the sourcemod UDP socket come from 127.0.0.0 instead of 127.0.0.1
            if not data or not ip.startswith('127.0.0') or not local_ip.startswith('127.0.0'):
                continue
            sock_external.sendto(data.encode(), (udp_external_ip, local_port))
    except KeyboardInterrupt: 
        pass
    finally:
        sock.close()
        sock_external.close()
#UDP redirecter welp
#screen -d -m -S udp_redirecter1 python3 udp_redirecter.py
