from os import listdir
from os.path import isfile, join
from datetime import datetime
from subprocess import check_output

ZONE_HEADER = """
;      _    ____ _   _ _____ _   _ _   _  ____
;     / \\  / ___| | | |_   _| | | | \\ | |/ ___|
;    / _ \\| |   | |_| | | | | | | |  \\| | |  _
;   / ___ \\ |___|  _  | | | | |_| | |\\  | |_| |
;  /_/   \\_\\____|_| |_| |_|  \\___/|_| \\_|\\____|
;
; --> Diese Datei wird von BundleWrap verwaltet! <--

$TTL 60
@       IN  SOA ns-1.kunbox.net.    hostmaster.kunbox.net. (
        {serial}
        3600
        3600
        86400
        300
        )
@       IN  NS  ns-1.kunbox.net.
        IN  NS  ns-2.kunbox.net.
"""

svc_systemd = {
    'bind9': {
        'needs': {
            'pkg_apt:bind9',
        },
    },
}

pkg_apt = {
    'bind9': {},
}

directories = {
    "/var/lib/bind/primary": {
        'group': 'bind',
        'needs': {
            'pkg_apt:bind9',
        },
        'owner': 'bind',
        'purge': True,
    },
    "/var/log/named": {
        'group': 'bind',
        'needs': {
            'pkg_apt:bind9',
        },
        'owner': 'bind',
    },
}

files = {
    "/etc/bind/keys.conf": {
        'content_type': 'mako',
        'group': 'bind',
        'mode': '0440',
        'context': {
            'keys': node.metadata.get('bind', {}).get('keys', []),
        },
        'triggers': {
            'svc_systemd:bind9:reload',
        },
        'needs': {
            'pkg_apt:bind9',
        },
    },
    "/etc/bind/named.conf.options": {
        'content_type': 'mako',
        'group': 'bind',
        'mode': '0440',
        'triggers': {
            'svc_systemd:bind9:reload',
        },
        'needs': {
            'pkg_apt:bind9',
        },
    },
}

if node.metadata.get('bind', {}).get('rndc', ''):
    files['/etc/bind/rndc.conf'] = {
        'mode': '0440',
        'source': 'rndc/{}'.format(node.metadata['bind']['rndc']),
        'content_type': 'mako',
        'triggers': {
            'svc_systemd:bind9:reload',
        },
    }

# this looks for zones either directly at data/bind/zones/ or in a subdirectory if so configured
zone_path = join(
    repo.path,
    'data', 'bind', 'files', 'zones',
    node.metadata.get('bind', {}).get('zone_path', ""),
)

primary_zones = set()

for zone in listdir(zone_path):
    if not isfile(join(zone_path, zone)) or zone.startswith(".") or zone.startswith("_"):
        continue

    output = check_output(['git', 'log', '-1', '--pretty=%ci', join(zone_path, zone)]).decode('utf-8').strip()
    serial = datetime.strptime(output, '%Y-%m-%d %H:%M:%S %z').strftime('%y%m%d%H%M')

    primary_zones.add(zone)

    files["/var/lib/bind/primary/{}".format(zone)] = {
        'content_type': 'mako',
        'context': {
            'header': ZONE_HEADER.format(serial=serial),
            'metadata_records': node.metadata.get('bind', {}).get('zones_primary', {}).get(zone, {}).get('records', []),
        },
        'mode': '0444',
        'owner': 'bind',
        'source': 'zones/{}'.format(join(node.metadata.get('bind', {}).get('zone_path', ""), zone)),
        'triggers': {
            'svc_systemd:bind9:reload',
        },
        'needs': {
            'pkg_apt:bind9'
        },
    }

primary_zones.union(set(node.metadata.get('bind', {}).get('zones_primary', {}).keys()))

files['/etc/bind/named.conf.local'] = {
    'content_type': 'mako',
    'context': {
        'primary_zones': list(primary_zones),
    },
    'group': 'bind',
    'triggers': {
        'svc_systemd:bind9:reload',
    },
    'needs': {
        'pkg_apt:bind9',
    },
}