#!/usr/bin/python3

from netaddr import IPNetwork
import csv
import sys

Section = "CDRN / TRN WAN"

fields = [
    'Section',
    'IP address',
    'Description',
    'Subnet',
    'Hostname'
]


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
        outRow['IP address'] = inRow['IP-Address']
        outRow['Description'] = inRow['Site-Name']
        outRow['Subnet'] = str(IPNetwork(inRow['IP-Address'] + '/' + inRow['Subnet-Mask']).cidr)
        outRow['Hostname'] = inRow['Site-Name'].split()[0] + '-SC200'

        csvWriter.writerow(outRow)
    inFile.close()

outFile.close()
