'''This module is used to write rules for Netfilter'''

# Used to handle timing information on created files
from datetime import datetime
# Used to handle timezone
from tzlocal import get_localzone
# hash functions for files
from hashfunc import sha1sum
from hashfunc import sha256sum

# Local system variables
timeFormat = "%H:%M:%S %Z"
myTimezone = get_localzone()

###########################################################################
def write_headers(filename, myOutput):
    """Write headers for the generated file contening hashes of the source CSV file."""

    # Compute source rules file hash
    print("# Source file rules sha1 hash is : " + sha1sum(filename), file=myOutput)
    print("# Source file rules sha256 hash is : " + sha256sum(filename), file=myOutput)
    print("", file=myOutput, flush=True)

###########################################################################
def write_rules(table, rules_reader, myOutput, defaultPolicy, __version__):
    """Write rules from CSV data and generate a iptables-restore compliant file
    for a specific table (examples are : filter, nat, mangle, raw)."""

    # Computer timestamp for every rules creation
    today = datetime.now(myTimezone)
    print("# Generated by CSV2Netfilter v"
          + __version__
          + " on "
          + today.strftime(timeFormat), file=myOutput)

    # Generate rules
    print("*" + table, file=myOutput)
    print(":INPUT " + defaultPolicy + " [0:0]", file=myOutput)
    print(":FORWARD " + defaultPolicy + " [0:0]", file=myOutput)
    print(":OUTPUT " + defaultPolicy + " [0:0]", file=myOutput)

    for row in rules_reader:
        # print("*******" + row['table'] + "*******")
        if row['table'] == table:
            if row['chain']:
                print('-A ' + row['chain'], file=myOutput, end=" ")
            if row['protocol']:
                print('-p ' + row['protocol'], file=myOutput, end=" ")
            if row['ipsource']:
                print('-s ' + row['ipsource'], file=myOutput, end=" ")
            if row['ipdest']:
                print('-d ' + row['ipdest'], file=myOutput, end=" ")
            if row['portsrc']:
                print('--sport ' + row['portsrc'], file=myOutput, end=" ")
            if row['portdest']:
                print('--dport ' + row['portdest'], file=myOutput, end=" ")
            if row['rule']:
                print('-j ' + row['rule'], file=myOutput, end=" ")
            if row['machine']:
                print('-m comment --comment "' + row['machine'] + '"', file=myOutput)

    print("COMMIT", file=myOutput)

    today = datetime.now(myTimezone)
    print("# Completed on " + today.strftime(timeFormat), file=myOutput, flush=True)
