#!/usr/bin/env python3
import os
from argparse import ArgumentParser

import yaml

from netboot_config.model import HostConfig, ConfigFile
from netboot_config.network import HostGroup, DefaultHost

if __name__ == '__main__':
    parser = ArgumentParser(description="Generator for KIWI based netboot config files")

    parser.add_argument('config_file', type=str, nargs=1)

    args = parser.parse_args()

    for config_file in args.config_file:

        hosts = []
        static_hosts = []

        with open(config_file, 'r') as stream:
            data_loaded = yaml.safe_load(stream)
            netboot_host = data_loaded['netboot']['host']

            for data in data_loaded['hostgroups']:
                host_group = HostGroup(data['prefix'], data['cidr'])
                for image in data['images']:
                    host_group.add_hosts(image['image_type'], image['offset'], image['count'])

                hosts += host_group.hosts()

            for host_name, host_ip in data_loaded['hosts'].items():
                static_hosts += [(host_ip, host_name)]

        hosts_file_path = 'hosts'
        with open(hosts_file_path, 'w') as hosts_file:
            hosts_file.write("""127.0.0.1	localhost
::1		localhost ip6-localhost ip6-loopback
ff02::1		ip6-allnodes
ff02::2		ip6-allrouters

""")
            for host in hosts:
                hosts_file.write("{}\t{}\n".format(host.ipv4_address, host.host_name))
            for host_entry in static_hosts:
                hosts_file.write("{}\t{}\n".format(host_entry[0], host_entry[1]))


        for host in hosts:
            host_config = HostConfig()
            host_name = host.host_name

            os.makedirs(host_name, exist_ok=True)
            host_name_file_path = os.path.join(host_name, 'hostname')
            with open(host_name_file_path, 'w') as host_name_file:
                host_name_file.write("{}\n".format(host.host_name))
            host_config.add(os.path.join('KIWI', host_name_file_path), '/etc/hostname')
            host_config.add(os.path.join('KIWI', hosts_file_path), '/etc/hosts')

            ConfigFile(host, host_config, netboot_host).write()

        host_config = HostConfig()
        ConfigFile(DefaultHost('base_image'), host_config, netboot_host).write()