#!/usr/bin/env python
# -*- coding: utf-8 -*-

#########################################################################
# eole-password - password management for eole
# Copyright © 2012 Pôle de Compétence 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
#########################################################################

""" EOLE Password script
    This is callable by a shell script to run password change operations.

"""

import argparse
from pyeole.password import Password
from pyeole.password import EolePwdError
from pyeole import ihm
from sys import stdin
from sys import exit as pexit
from sys import argv

ALOG_FILE = "/var/cache/eole-password/eolepassword.alog"


def set_arguments(parser):
    """ Setup all options for the script
    """
    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s v0.0.1')
    parser.add_argument('-c', '--config-dir',
                        help='direcotry for configuration',
                        default='/etc/eole-password')
    parser.add_argument('-C', '--configuration',
                        help='Inline Configuration (Yaml format)')
    parser.add_argument('-m', '--main-configuration',
                        help='Main configuration for eolepassword',
                        default='/etc/eole-password/main.cfg')
    parser.add_argument('-l', '--action-log', help='action log file',
                        default=ALOG_FILE)

    parser.add_argument('--mysql',
                        help='Change mysql root password',
                        action="store_true")

    parser.add_argument('--pgsql',
                        help='Change postgresql root password',
                        action="store_true")

# Replace by pyeole/ihm.py question_oui_non()
def yes_no(question):
    """ Ask yes/no question on tty
    """
    res = ihm.question_ouinon(question, interactive=True, default='non')
    if res == "yes":
        return "True"
    elif res == "non":
        return "False"

def main():
    """ Main program, parse arguments and run actions
    """
    parser = argparse.ArgumentParser(description='Eole Password Changer.')
    set_arguments(parser)
    args = parser.parse_args()

    if len(argv) == 1:
        parser.print_help()
        pexit(1)

    try:
        if args.mysql:
            pwd_handler = Password(args.action_log,
                                   args.config_dir,
                                   args.main_configuration,
                                   {'user': 'root',
                                    'host': 'all',
                                    'type': 'mysql',
                                    'mode': 'manual',
                                    'to_change': None})
            pwd_handler.process()
            question = "Automatic password renew for other accounts ?"
            if yes_no(question):
                pwd_handler.process("mysql")
        elif args.pgsql:
            pwd_handler = Password(args.action_log,
                                   args.config_dir,
                                   args.main_configuration,
                                   {'user': 'root',
                                    'host': 'all',
                                    'type': 'pgsql',
                                    'mode': 'manual',
                                    'to_change': None})
            pwd_handler.process()
            question = "Automatic password renew for other accounts ?"
            if yes_no(question):
                pwd_handler.process("pgsql")

        else:
            pwd_handler = Password(args.action_log,
                                   args.config_dir,
                                   args.main_configuration)
            pwd_handler.process()
    except EolePwdError as err:
        pexit(2)

main()
