#!/usr/bin/python3

# pylint: disable=invalid-name,pointless-string-statement,import-error,protected-access
from os.path import exists, join, basename, isdir, isfile
from os import system, chmod
from socket import gethostname
import shutil

from yaml import load
from spacewalk.common import rhnConfig
from salt.ext import six
from Cheetah.Template import Template


TEMPLATES_DIR = '/usr/share/cobbler/installer_templates'
MODULES_TEMPLATE = join(TEMPLATES_DIR, 'modules.conf.template')
SETTINGS_TEMPLATE = join(TEMPLATES_DIR, 'settings.template')
DEFAULTS = join(TEMPLATES_DIR, 'defaults')

CONFIG_DIR = '/etc/cobbler/'
MODULES = join(CONFIG_DIR, 'modules.conf')
SETTINGS = join(CONFIG_DIR, 'settings')

TEMP_MODULES = '/tmp/modules.conf'
TEMP_SETTINGS = '/tmp/settings'

def loadFile(fl):
    return load(open(fl).read())

def copy(src, dest):
    if exists(dest):
        if isfile(dest):
            shutil.copy(dest, dest + ".old")
        elif isdir(dest) and isfile(src) and exists(join(dest, basename(src))):
            shutil.copy(join(dest,basename(src)), join(dest,basename(src)) + ".old")
    shutil.copy(src, dest)

def ask_yes_no(question, default_val = None):
    if default_val and default_val.lower() == 'y':
        default_val = 'y'
        default_q   = '[Y/n]'
    else:
        default_val = 'n'
        default_q   = '[y/N]'

    if six.PY3:
        raw_input = input

    ans = raw_input(question + " " + default_q + "?")
    if not ans:
        return default_val == 'y'

    return ans.lower() == 'y'

def gen_template(template, answers, output):
    t = Template(file=template, searchList=answers)
    with open(output, 'w') as tfh:
        tfh.write(t.respond())

def main():
    answers = dict(loadFile(DEFAULTS))
    answers['server'] = gethostname()
    answers['next_server'] = answers['server']
    answers['redhat_management_server'] = answers['server']
    answers['redhat_management_type'] = 'site'
    answers['authn_module'] = 'authn_spacewalk'
    answers['pxe_once'] = '1'
    gen_template(SETTINGS_TEMPLATE, answers, TEMP_SETTINGS)
    gen_template(MODULES_TEMPLATE, answers, TEMP_MODULES)
    copy(TEMP_SETTINGS, SETTINGS)
    chmod(SETTINGS, 0o644)
    copy(TEMP_MODULES, MODULES)
    chmod(MODULES, 0o644)

    cobbler_host = False
    with open(rhnConfig._CONFIG_FILE) as fh:
        for line in fh.readlines():
            if '=' in line and line.startswith('cobbler.host'):
                cobbler_host = True
                break
    if not cobbler_host:
        with open(rhnConfig._CONFIG_FILE, 'a') as fh:
            fh.write('cobbler.host = {}\n'.format(answers['server']))
    system("cobbler sync")


if __name__=="__main__":
    main()


"""

=head1 NAME

cobbler-setup

=head1 SYNOPSIS

        cobbler-setup

=head1 DESCRIPTION

The B<cobbler-setup> program generates configuration files for cobbler
in F</etc/cobbler>, based on templates in
F</usr/share/cobbler/installer_templates>.

The tool is generally called automatically by Spacewalk's
B<spacewalk-setup>.

=back

=head1 SEE ALSO

spacewalk-setup(1)

=cut

"""
