#!/usr/bin/env python2
# -*- coding: utf-8 -*-
###########################################################################
# Eole NG - 2012
# Copyright Pole de Competence Eole  (Ministere Education - Academie Dijon)
# Licence CeCill  cf /root/LicenceEole.txt
# eole@ac-dijon.fr
###########################################################################
""" EoleDB the new database manager for EOLE
"""
import argparse
from os import listdir, path
from termcolor import cprint, colored
import yaml

from eoledb.eoledbconnector import EoleDbConnector
from eoledb.eoledberrors import UnsupportedDatabase


def load_conf(cpath):
    """ Load configuration from yaml file
    """
    mainconf = yaml.load(file(cpath))

    if mainconf is None:
        mainconf = {}
    elif isinstance(mainconf, dict) is False:
        msg = "[ERROR] Configuration file format error !"
        msg += "\n{0} is not a valid YAML file".format(cpath)
        raise Exception(msg)

    if 'dbcont' not in mainconf:
        mainconf['dbcont'] = None
    if 'dbhost' not in mainconf:
        mainconf['dbhost'] = None
    if 'dbport' not in mainconf:
        mainconf['dbport'] = None
    if 'dbroot' not in mainconf:
        mainconf['dbroot'] = None
    if 'dbrootpwd' not in mainconf:
        mainconf['dbrootpwd'] = None
    if 'dbtype' not in mainconf:
        mainconf['dbtype'] = None
    if 'dbcliconf' not in mainconf:
        mainconf['dbcliconf'] = None
    if 'client_hosts' not in mainconf:
        mainconf['client_hosts'] = None

    return mainconf


def usage():
    """ Print command help message
    """
    print "Usage:"
    print "\t -c file # Configuration File"


def run_change_password(conn, local_conf, bdir):
    """ Run all the changing password opérations
    """
    print "\t>>> Passwords" ,
    if conn.change_passwords(local_conf, bdir):
        print "\t[{0}]".format(colored('OK','green'))
    else:
        print "\t[{0}]".format(colored('NA','blue'))

def main():
    """ EoleDB main program
    """
    parser = argparse.ArgumentParser(description='Eole Database generator.')
    parser.add_argument('-c', '--config', metavar='CONFIG_FILE',
                        default='/etc/eole/eole-db.conf',
                        help='eole database configuration file)')
    parser.add_argument('-d', '--dbdir', metavar='DB_CONFIG_DIR',
                        default='/etc/eole/eole-db.d/',
                        help='eole database configuration directory)')
    parser.add_argument('-i', '--interactive', action='store_true',
                        default=False, help='eole database manager interactive mode')
    parser.add_argument('-b', '--backup-dir', metavar="PW_BACKUP_DIR",
                        default='/var/backups/eoledb',
                        help='eole database directory to store backups of changed files')
    args = parser.parse_args()

    if args.interactive:
        print "Not implemented yet"

    if args.config:
        mainconf = load_conf(args.config)

        for cfile in listdir(args.dbdir):
            if cfile.endswith(".yml"):
                conn = None
                try:
                    conn = EoleDbConnector(mainconf, config=u'{0}/{1}'.format(args.dbdir, cfile))()
                except UnsupportedDatabase as err:
                    print err
                except AttributeError as err:
                    print err
                if conn:
                    print("{0} : ".format(conn.dbname.upper()))
                    local_conf = {'file':  path.join(args.dbdir, cfile),
                                  'pattern': 'dbpass: "'}
                    if args.backup_dir:
                        run_change_password(conn, local_conf, args.backup_dir)
                    else:
                        run_change_password(conn, local_conf, None)

                    print "\t>>> Create " ,
                    if conn.instance_db():
                        print "\t[{0}]".format(colored('OK','green'))
                    else:
                        print "\t[{0}]".format(colored('NA','blue'))
                    print "\t>>> Update " ,
                    if conn.update_db():
                        print "\t[{0}]".format(colored('OK','green'))
                    else:
                        print "\t[{0}]".format(colored('NA','blue'))
                    print "\n"
    else:
        parser.error("options -c is mandatory")


if __name__ == "__main__":
    main()
