#!/usr/bin/python
# -*- coding: utf-8 -*-
#  copyright 2014 Cornelius Kölbel
#  License:  AGPLv3
#  contact:  http://www.privacyidea.org
#
# This code is free software; you can redistribute it and/or
 # License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU AFFERO GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
  Description:  This is the setup tool for privacyidea
'''

VERSION = '1.3'
DESCRIPTION = __doc__


import subprocess
import ConfigParser
import argparse
import smtplib
import binascii
from email.mime.text import MIMEText
import sys
import os
import re
import StringIO
from privacyidea.lib.ext import nginxparser
from privacyidea.lib.appliance import NginxConfig
from privacyidea.lib.appliance import PrivacyIDEAConfig
import os.path
import pprint
from subprocess import call 

def nginx_enable(args):
    nconfig = NginxConfig()
    nconfig.enable()

def nginx_disable(args):
    nconfig = NginxConfig()
    nconfig.disable()

def nginx_view(args):
    nconfig = NginxConfig()
    print "privacyidea config is active: %s, %s " % nconfig.is_active()
    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(nconfig.get())
    
def create_certificates(args):
    nconfig = NginxConfig()
    nconfig.create_certificates()

def privacyidea_view(args):
    pConfig = PrivacyIDEAConfig(args.file)
    print """
    Retrieving OTP values is allowed: %s
    The secret key file             : %s
    The administrator file          : %s
    List of the admin realms        : %s
    Database configuration          : %s
    Loglevel                        : %s
    """ % (pConfig.get_getotp(),
           pConfig.get_keyfile(),
           pConfig.get_adminfile(),
           pConfig.get_adminrealms(),
           pConfig.get_DB(),
           pConfig.get_loglevel())
    
def privacyidea_init(args):
    pConfig = PrivacyIDEAConfig(args.file,
                                init=True)
    pConfig.save()
    privacyidea_view(args)
    
def privacyidea_set(args):
    pConfig = PrivacyIDEAConfig(args.file)  
    if args.loglevel:
        pConfig.set_loglevel(args.loglevel)
    if args.dbuser:
        pConfig.set_DB({"user": args.dbuser})
    if args.dbpassword:
        pConfig.set_DB({"password": args.dbpassword})
    if args.dbtype:
        pConfig.set_DB({"type": args.dbtype})
    if args.dbhost:
        pConfig.set_DB({"host": args.dbhost})
    if args.dbname:
        pConfig.set_DB({"database": args.dbname})
    if args.adminrealms:
        pConfig.set_adminrealms(args.adminrealms)
    if args.adminfile:
        pConfig.set_adminfile(args.adminfile)
    if args.getotp:
        pConfig.toggle_getotp()
    pConfig.save()
    privacyidea_view(args)


def create_arguments():
    parser = argparse.ArgumentParser(description=DESCRIPTION,
                                     fromfile_prefix_chars='@')
    parser.add_argument("-f", "--file",
                        help="The privacyidea.ini file.",
                        required=False)
    parser.add_argument("-v", "--version",
                        help="Print the version of the program.",
                        action='version', version='%(prog)s ' + VERSION)
    
    subparsers = parser.add_subparsers(help="The available commands. Running "
                                       "<command> -h will give you a detailed "
                                       "help on this command.",
                                       title="COMMANDS",
                                       description="The command line tool "
                                       "requires one command, to know what "
                                       "action it should take")
    
    ################################################################
    #
    # privacyidea.ini commands
    #
    privacyidea_parser = subparsers.add_parser("privacyidea",
                                               help="configure privacyidea "
                                               "application in privacyidea.ini."
                                               )
    token_sub = privacyidea_parser.add_subparsers()
    
    # privacyidea
    p_pidea = token_sub.add_parser('view',
                                   help='View the privacyidea config.')
    p_pidea.set_defaults(func=privacyidea_view)
    
    p_pidea = token_sub.add_parser('init',
                                   help="initiate a ini-file template")
    p_pidea.set_defaults(func=privacyidea_init)
    
    p_pidea = token_sub.add_parser('set',
                                   help='set some things.')
    p_pidea.set_defaults(func=privacyidea_set)
    p_pidea.add_argument("-l", "--loglevel",
                         help="Set the log level to DEBUG, INFO, WARN "
                         "or ERROR.")
    p_pidea.add_argument("--dbuser",
                         help="The database user")
    p_pidea.add_argument("--dbpassword",
                         help="The database password")
    p_pidea.add_argument("--dbhost",
                         help="The hostname of the database connection")
    p_pidea.add_argument("--dbtype",
                         help="The type like 'mysql'")
    p_pidea.add_argument("--dbname",
                         help="The database name")
    
    p_pidea.add_argument("--adminrealms",
                         help="comma seperated list of admin realms")
    p_pidea.add_argument("--adminfile",
                         help="file with admin users")
    p_pidea.add_argument("--getotp",
                         action="store_true",
                         help="Toggle if retrieving OTP values is allowed "
                         "or not.")
    
    # nginx
    nginx_parser = subparsers.add_parser("nginx",
                                         help="configure webserver "
                                         "nginx.")
    token_sub = nginx_parser.add_subparsers()
    p_pidea = token_sub.add_parser("enable",
                                   help="Enable privacyidea server")
    p_pidea.set_defaults(func=nginx_enable)
    p_pidea = token_sub.add_parser("disable",
                                   help="Disable privacyidea server")
    p_pidea.set_defaults(func=nginx_disable)
    p_pidea = token_sub.add_parser("view",
                                   help="View the nginx config")
    p_pidea.set_defaults(func=nginx_view)
    
    p_pidea = token_sub.add_parser("createcert",
                                   help="Create certificates")
    p_pidea.set_defaults(func=create_certificates)
    
    
    args = parser.parse_args()
    return args

    
def main():
    args = create_arguments()
    args.func(args)


if __name__ == '__main__':
    main()