#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
##########################################################################
# creole.containers - management of LXC containers
# Copyright © 2012,2013 Pôle de compétences EOLE <eole@ac-dijon.fr>
#
# License CeCILL:
#  * in french: http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html
#  * in english http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
##########################################################################

"""Generate LXC containers

`gen_conteneurs` generate the base LXC chroot and instanciate basic
LXC configuration files.

"""

import sys
import argparse
import traceback
from os import system, remove
from os.path import isdir, isfile

from pyeole import scriptargs
from pyeole.log import init_logging
from pyeole import ihm
from pyeole.service import unmanaged_service
from pyeole.service.error import ServiceError
from pyeole.i18n import i18n
_ = i18n('eole-common')

from creole.config import gen_conteneurs_needed
from creole.reconfigure import containers, install_packages, \
   container_instance_lockfile, options, restart_creoled

_CACHE_DIR = '/opt/cache'

def parse_cmdline():
    """Parse commande line.
    """
    parser = argparse.ArgumentParser(description="Génération et configuration"
                                     " des conteneurs LXC",
                                     parents=[scriptargs.logging()])
    opts = parser.parse_args()

    options.update_from_cmdline(force_options={'interactive': True})
    if opts.verbose:
        opts.log_level = 'info'
    if opts.debug:
        opts.log_level = 'debug'

    return opts

def user_exit(*args, **kwargs):
    """
    sortie utilisateur "propre"
    """
    ihm.print_orange(_('! Abandoning container generation !'))
    ihm.print_orange(_('System may be in an incoherent state.\n\n'))
    sys.exit(1)

def main():
    """Setup environnment and run LXC generation.
    """

    options = parse_cmdline()
    try:
        log = init_logging(level=options.log_level)
        try:
            unmanaged_service('status', 'lxc-net', 'upstart')
        except ServiceError:
            unmanaged_service('start', 'lxc-net', 'upstart',
                              display='console')
        ihm.catch_signal(user_exit)
        restart_creoled()
        if isdir(_CACHE_DIR):
            question = _("LXC cache already exists, do you want to remove it ?")
            try:
                if ihm.question_ouinon(question) == 'oui':
                    system('rm -rf {0}'.format(_CACHE_DIR))
            except EOFError:
                user_exit()

        open(container_instance_lockfile, 'w').write('')
        if isfile(gen_conteneurs_needed):
            remove(gen_conteneurs_needed)
        containers(minimal=True, log_=log)
        ihm.print_title(_("Installing additional packages"))
        if options.log_level in ['info', 'debug']:
            silent = False
        else:
            silent = True
        install_packages(silent=silent)
        ihm.print_title(_("Containers generation terminated"))
    except Exception as err:
        if options.debug:
            log.debug(traceback.format_exc())
        else:
            log.error(err)
        sys.exit(1)
    sys.exit(0)

if __name__ == '__main__':
    main()
