#!/usr/bin/python3

from netaddr import IPNetwork
import csv
import sys
import re

Section = "CDRN / TRN WAN"

fields = [
    'Section',
    'Subnet',
    'Mask',
    'Description',
]

subnets = []

inFilePath = sys.argv[1]

if len(sys.argv) == 3:
    outFile = open(sys.argv[2], 'w')
else:
    outFile = sys.stdout

csvWriter = csv.DictWriter(outFile, fieldnames=fields,
    delimiter=',', quotechar='"',
    quoting=csv.QUOTE_MINIMAL)

csvWriter.writeheader()

with open(inFilePath, 'r', newline='') as inFile:
    csvReader = csv.DictReader(inFile)
    outRow = {}

    for inRow in csvReader:
        outRow['Section'] = Section
        subnet = IPNetwork(inRow['IP-Address'] + '/' + inRow['Subnet-Mask']).cidr
        if subnet in subnets:
            continue
        subnets.append(subnet)
        outRow['Subnet'] = str(subnet)
        outRow['Mask'] = inRow['Subnet-Mask']
        try:
            outRow['Description'] = re.search(r"(([a-zA-Z]+S\d)|(C[a-zA-Z]+\d+)|(T[a-zA-Z]+)|([a-zA-Z]+(-Core)?))([\- ]+\d )?.*", inRow['Site-Name']).group(1) + '-SC200'
        except AttributeError:
            print(inRow['Site-Name'])
            outRow['Description'] = inRow['Site-Name']

        csvWriter.writerow(outRow)
    inFile.close()

outFile.close()
