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

from netboot_config import Config
from netboot_config.model import HostConfig, ConfigFile
from netboot_config.network import 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()

    config_file = args.config_file[0]

    config = Config(config_file)

    hosts_file_path = 'hosts'
    with open(hosts_file_path, 'w') as hosts_file:
        hosts_file.write(config.render_hosts())

    for host in config.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')
        for config_entry in host.config:
            host_config.add(os.path.join('KIWI', config_entry[0]), config_entry[1])

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

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