#!/usr/bin/env python
import subprocess, shutil, datetime

RFile = open(r"rules.txt")
R1File = open(r"rules2.txt")
BegTab = open(r"BegTab.txt")
OutFile = open(r"/home/ruler/reconfig/IPTBegin.txt", "w")


def CloseFile():
    RFile.close()
    R1File.close()
    BegTab.close()
#    OutFile.close()


for line in BegTab:
    OutFile.write(line)
OutFile.write("\n")

OutFile.close()

OutFile = open(r"/home/ruler/reconfig/IPTBegin.txt", "a")

for line in RFile:
    linecut = line[:-1]
    STR = linecut.split(",")
    OutInt = "error"
    if STR[1] == "46.228.10.26":
        OutInt = "eth1"
    if STR[1] == "46.228.10.98":
        OutInt = "eth4"
    if STR[1] == "178.238.19.206":
        OutInt = "eth3"
    RTxt = "-A PREROUTING -p " + STR[0] + " -m " + STR[0] + " -d " + STR[1] + "/32 -i " + OutInt + " --dport " + STR[2] + " -j DNAT --to-destination " + STR[3] + ":" + STR[4] + '\n'
    OutFile.write(RTxt)

for line in R1File:
    linecut = line[:-1]
    STR = linecut.split(",")
    R1Txt = "-A PREROUTING -p " + STR[0] + " -m " + STR[0] + " -s " + STR[1] + " -i " + STR[2] + " --dport " + STR[3] + " -j DNAT --to-destination " + STR[4] + ":" + STR[5]  + '\n'
    OutFile.write(R1Txt)
	

CloseFile()
OutFile.close()
print("Content-type: text/html\n")
print("<p>NAT config has been built</p>")
print("""<p><a href="NatDisp.py">Return back</a></p>""")
print("""<meta http-equiv="refresh" content="5;NatDisp.py">""")
