#!/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/>.
"""
text dialog based setup tool to configure the privacyIDEA basics.
"""

import locale
import argparse
import sys
import time
from dialog import Dialog
from privacyidea.lib.appliance import (Backup,
                                       FreeRADIUSConfig,
                                       PrivacyIDEAConfig,
                                       NginxConfig,
                                       DEFAULT_CONFIG)

DESCRIPTION = __doc__
VERSION = "1.5"


class pSetup(object):
    
    def __init__(self, config=None):
        self.data_changed = False
        if config:
            self.config_file = config
        else:
            self.config_file = DEFAULT_CONFIG
            
        self.pConfig = PrivacyIDEAConfig(self.config_file)
        
        self.NginxConfig = NginxConfig()
        
        self.Backup = Backup()
        
        try:
            self.RadiusConfig = FreeRADIUSConfig()
        except:
            # No Radius Server available
            self.RadiusConfig = None
                
        self.d = Dialog(dialog="dialog")
        
        
    def main_menu(self):
        choices=[("privacyidea", "",
                  "Configure privacyIDEA application "
                  "stuff like administrators."),
                  ("Webserver","",
                  "Configure settings concerning "
                  "the webservice like the SSL "
                  "certificates.")]
        if self.RadiusConfig:
            choices.append( ("FreeRADIUS","",
                             "Configure RADIUS settings like "
                             "the RADIUS clients.") )
        choices.append(("Backup and Restore","",
                        "Backup or Restore of privacyIDEA"
                        "configuration and database and"
                        "RADIUS clients."))
        while 1:
            code, tags = self.d.menu("Which subject do you want to configure?",
                                     choices=choices,
                                     backtitle="privacyIDEA configuration",
                                     cancel="Exit",
                                     item_help=1)
            if code == self.d.DIALOG_OK:
                print tags
                if tags == "Webserver":
                    self.webserver_menu()
                elif tags == "privacyidea":
                    self.privacyidea_menu()
                elif tags == "FreeRADIUS":
                    self.radius_menu()
                elif tags.startswith("Backup"):
                    self.backup_menu()
                    
            else:
                # End
                if self.data_changed:
                    self.webserver_restart()
                break
    
    def privacyidea_menu(self):
        while 1:
            code, tags = self.d.menu("Configure privacyidea",
                                     choices=[("view config",
                                               "",""),
                                              ("initialize ini-file",
                                               "",
                                               "Create a new ini-file with "
                                               "default values."),
                                              ("loglevel",
                                               "",
                                               ""),
                                              ("getotp", "", ""),
                                              ("admin realms", "", ""),
                                              ("manage admins", "", ""),
                                              ("database", "", ""),
                                              ("encryption key", "", ""),
                                              ("signing key", "", "")],                                     
                                     menu_height=22,
                                     backtitle="privacyIDEA configuration",
                                     item_help=1)
        
            if code == self.d.DIALOG_OK:
                if tags.startswith("loglevel"):
                    self.privacyidea_loglevel()
                elif tags.startswith("getotp"):
                    self.privacyidea_getotp()
                elif tags.startswith("view"):
                    self.privacyidea_view()
                elif tags.startswith("initialize"):
                    self.privacyidea_initialize()
                elif tags.startswith("admin realms"):
                    self.privacyidea_adminrealms()
                elif tags.startswith("admin file"):
                    self.privacyidea_adminfile()
                elif tags.startswith("manage admins"):
                    self.privacyidea_admins()
                elif tags.startswith("encryption"):
                    self.privacyidea_enckey()
                elif tags.startswith("signing"):
                    self.privacyidea_sign()
                elif tags.startswith("database"):
                    self.privacyidea_database()
            else:
                break
       
    def privacyidea_database(self):
        bt="Configure the database connection"
        while 1:
            current_config = self.pConfig.get_DB()
            code, tags = self.d.menu("The current database configuration "
                                     "string is %s" % current_config,
                                     choices=[("reset locally",
                                               "let privacyidea recreate the config"),
                                              ("init tables", "create tables"),
                                              ("---", "-------------------"),
                                              ("type",
                                               "set the driver like mysql or psql"),
                                              ("user",
                                               "set the database user"),
                                              ("password",
                                               "set the database password"),
                                              ("host",
                                               "set the database host"),
                                              ("name",
                                               "set the database name"),
                                              ],
                                     backtitle=bt)
            if code == self.d.DIALOG_OK:
                if tags.startswith("reset"):
                    self.privacyidea_db_reset()
                elif tags.startswith("init"):
                    self.privacyidea_db_init()
                elif tags.startswith("type"):
                    self.privacyidea_db_type()
                elif tags.startswith("user"):
                    self.privacyidea_db_user()
                elif tags.startswith("password"):
                    self.privacyidea_db_password()
                elif tags.startswith("host"):
                    self.privacyidea_db_host()
                elif tags.startswith("name"):
                    self.privacyidea_db_name()
            else:
                break
            
    def privacyidea_db_init(self):
        db_connect = self.pConfig.get_DB()
        code = self.d.yesno("Do you want to recreate the tables? "
                            "Existing data will not be lost. Only new tables " 
                            "in the database scheme will be created on %s" %
                            db_connect,
                            width=70,
                            backtitle="Create database tables")
        if code == self.d.DIALOG_OK:
            r, out = self.pConfig.DB_init()
            if r:
                self.d.msgbox("Created database tables.")
            else:
                self.d.scrollbox("Error creating database tables: %s" % out)
        
    def privacyidea_db_reset(self):
        code = self.d.yesno("Do you want to reset the database configuration? "
                            "This will create a new user on the locally "
                            "running mysql server.",
                            backtitle="Reset database configuration",
                            defaultno=1)
        if code == self.d.DIALOG_OK:
            res, dbconfig = self.pConfig.DB_create()
            if res:
                self.pConfig.set_DB({"type": "mysql",
                                     "host": "localhost",
                                     "user": dbconfig[1],
                                     "password": dbconfig[2],
                                     "database": dbconfig[0]})
                self.pConfig.save()
                self.data_changed = True
                r, out = self.pConfig.DB_init()
                if r:
                    self.d.msgbox("Database created.")
                else:
                    self.d.scrollbox("Error creating database tables: %s" % out)
            else:
                self.d.scrollbox("Failed to create database.\n %s" % dbconfig)
        
        
    def privacyidea_db_type(self):
        db_connect = self.pConfig.get_DB()
        try:
            dialect = db_connect.split(":")[0]
        except IndexError:
            dialect = mysql
        
        code, tags = self.d.radiolist("Select the database dialect you want "
                                "the token data to be stored at (%s)" %
                                db_connect,
                                choices=[("mysql", "",
                                          int(dialect=="mysql")),
                                         ("sqlite", "",
                                          int(dialect=="sqlite")),
                                         ("postgresql", "",
                                          int(dialect=="postgresql")),
                                         ("postgtresql+psycopg2", "",
                                          int(dialect=="postgtresql+psycopg2")),
                                         ("oracle", "",
                                          int(dialect=="oracle"))],
                                backtitle="Select database dialect")
        
        if code == self.d.DIALOG_OK:
            self.pConfig.set_DB({"type" : tags})
            self.pConfig.save()
            self.data_changed = True
        
    def privacyidea_db_user(self):
        db_dict = self.pConfig.get_DB_dict()
        code, tags = self.d.inputbox("Enter the name of the database user",
                                     init=db_dict.get("user") or "",
                                     backtitle="Configure database connection")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_DB({"user": tags})
            self.pConfig.save()
            self.data_changed = True
    
    
    def privacyidea_db_password(self):
        db_dict = self.pConfig.get_DB_dict()
        code, tags = self.d.inputbox("Enter the password of the database user",
                                     init=db_dict.get("password") or "",
                                     backtitle="Configure database connection")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_DB({"password": tags})
            self.pConfig.save()
            self.data_changed = True
    
    def privacyidea_db_host(self):
        db_dict = self.pConfig.get_DB_dict()
        code, tags = self.d.inputbox("Enter the hostname of the database",
                                     init=db_dict.get("host") or "",
                                     backtitle="Configure database connection")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_DB({"host": tags})
            self.pConfig.save()
            self.data_changed = True
    
    def privacyidea_db_name(self):
        db_dict = self.pConfig.get_DB_dict()
        code, tags = self.d.inputbox("Enter the name of the database",
                                     init=db_dict.get("database") or "",
                                     backtitle="Configure database connection")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_DB({"database": tags})
            self.pConfig.save()
            self.data_changed = True
            
    def privacyidea_admins(self):
        while 1:
            admins = [("Add new admin", "Add a new administrator")]
            admins_from_file = self.pConfig.get_admins()
            for admin in admins_from_file:
                admins.append( admin )
            code, tags = self.d.menu("You can select an existing administrator "
                                     "to either delete it or change the " 
                                     "password or create a new admin",
                                     choices=admins,
                                     backtitle="Manage administrators")
            
            if code == self.d.DIALOG_OK:
                if tags == "Add new admin":
                    self.privacyidea_admin_add()
                else:
                    self.privacyidea_admin_manage(tags)
            else:
                break
            
    def privacyidea_admin_manage(self, admin_name):
        bt="Manage administrator"
        code, tags = self.d.menu("Manage admin %s" % admin_name,
                                 choices=[("Delete admin", ""),
                                          ("Change password", "")],
                                 backtitle=bt)
        if code == self.d.DIALOG_OK:
            if tags.startswith("Delete"):
                self.d.yesno("Do you really want to delete the "
                             "administrator %s?" % admin_name)
                self.pConfig.delete_admin(admin_name)
                
            if tags.startswith("Change"):
                password = self.privacyidea_admin_password(admin_name)
                pass
            
    def privacyidea_admin_password(self, admin_name, create=False):
        bt = "Setting password for administrator %s" % admin_name
        password = None
        while 1:
            code, password1 = self.d.passwordbox("Enter the password for the "
                                                 "administrator %s" % admin_name,
                                                 backtitle=bt)
                
            if code == self.d.DIALOG_OK:
                code, password2 = self.d.passwordbox("Repeat the password",
                                                     backtitle=bt)
                if code == self.d.DIALOG_OK:
                    if password1 != password2:
                        self.d.msgbox("The passwords do not match. "
                                      "Please try again.")
                    else:
                        password = password1
                        if create:
                            self.pConfig.set_admin(admin_name,
                                                   password,
                                                   description="")
                        else:
                            self.pConfig.update_admin(admin_name,
                                                      password,
                                                      description="")
                        break
                else:
                    break
            else:
                break
        return password 
            
    def privacyidea_admin_add(self):
        bt="Add a new administrator"
        code, admin_name = self.d.inputbox("The username of the new "
                                     "administrator",
                                     backtitle=bt)
        
        if code == self.d.DIALOG_OK:
            password = self.privacyidea_admin_password(admin_name,
                                                       create=True)
            
       
    def privacyidea_adminrealms(self):
        adminrealms = self.pConfig.get_adminrealms()
        code, tags = self.d.inputbox("You may enter a comma seperated list "
                                     "of realms that are recognized as "
                                     "admin realms.",
                                     init=adminrealms,
                                     width=40,
                                     backtitle="configure admin realms")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_adminrealms(tags)
            self.pConfig.save()
            self.data_changed = True
         
    def privacyidea_initialize(self):
        code = self.d.yesno("Do you want to initialize "
                            "the config file? Old privacyIDEA "
                            "configurations will be overwritten!",
                            backtitle="Initialize privacyIDEA configuration",
                            defaultno=1)
        if code == self.d.DIALOG_OK:
            self.pConfig.initialize()
            self.pConfig.save()
            self.data_changed = True
            
    def privacyidea_enckey(self):
        code = self.d.yesno("Do you want to create a new encryption key? "
                            "All token keys will not be readable anymore!",
                            backtitle="Create a new encryption key.",
                            defaultno=1)
        if code == self.d.DIALOG_OK:
            r, f = self.pConfig.create_encryption_key()
            if r:
                self.d.msgbox("Successfully created new encryption key %s." %
                              f)
            else:
                self.d.msgbox("Failed to create new encryption key %s!" %
                              f)
            
    def privacyidea_sign(self):
        code = self.d.yesno("Do you want to create a new audit trail "
                            "signing key? "
                            "Older audit entries can not be verified anymore.",
                            backtitle="Create a new signing key.",
                            defaultno=1)
        if code == self.d.DIALOG_OK:
            r, f = self.pConfig.create_audit_keys()
            if r:
                self.d.msgbox("Successfully created new audit keys %s." %
                              f)
            else:
                self.d.msgbox("Failed to create new audit keys %s!" %
                              f)
        
    def privacyidea_loglevel(self):
        loglevel = self.pConfig.get_loglevel()
        code, tags = self.d.radiolist("choose a loglevel",
                                      choices=[("DEBUG", "", 
                                                int(loglevel=="DEBUG")),
                                               ("INFO", "",
                                                int(loglevel=="INFO")),
                                               ("WARN", "Warnings",
                                                int(loglevel=="WARN")),
                                               ("ERROR", "",
                                                int(loglevel=="ERROR"))],
                                      backtitle="privacyIDEA loglevel.")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_loglevel(tags)
            self.pConfig.save()
            self.data_changed = True

    
    def privacyidea_getotp(self):
        otp = self.pConfig.get_getotp()
        code, tags = self.d.radiolist("Allow retrieving OTP values",
                                      choices=[("Allow",
                                                "OTP values can be retrieved",
                                                int(otp)),
                                               ("Deny",
                                                "OTP values can not be "
                                                "retreived",
                                                int(not otp))],
                                      backtitle="getOTP configuration")
        if code == self.d.DIALOG_OK:
            self.pConfig.set_getotp(tags == "Allow")
            self.pConfig.save()
            self.data_changed = True
    
    def privacyidea_view(self):
        text = """
    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
    """ % (self.pConfig.get_getotp(),
           self.pConfig.get_keyfile(),
           self.pConfig.get_adminfile(),
           self.pConfig.get_adminrealms(),
           self.pConfig.get_DB(),
           self.pConfig.get_loglevel())
        self.d.scrollbox(text)
    
    def backup_menu(self):
        bt = "Backup and Restore configuration"
        while 1:
            code, tags = self.d.menu("Backup and Restore",
                                     choices=[("Configure backup", ""),
                                              ("Backup now", ""),
                                              ("View Backups", "")],
                                     backtitle=bt)
            if code == self.d.DIALOG_OK:
                if tags.startswith("Configure"):
                    self.backup_config()
                elif tags.startswith("Backup"):
                    self.backup_now()
                elif tags.startswith("View Backup"):
                    self.backup_view()
            else:
                break
            
    def backup_config(self):
        '''
        Display the cronjobs of user privacyidea
        '''
        bt = "Define backup times"
        while 1:
            cronjobs = self.Backup.get_cronjobs()
            choices = [("Add new backup date", "")]
            for cronjob in cronjobs:
                if cronjob.get("user") == "privacyidea":
                    comment = "backup job."
                    if cronjob.get("minute", "*") != "*":
                        comment = "hourly backup job."
                    if cronjob.get("hour", "*") != "*":
                        comment = "daily backup job."
                    if cronjob.get("dow", "*") != "*":
                        comment = "weekly backup job."
                    if cronjob.get("dom", "*") != "*":
                        comment = "monthly backup job."
                    if cronjob.get("month", "*") != "*":
                        comment = "yearly backup job."
                    choices.append(("%s %s %s %s %s" % (cronjob.get("minute", "*"),
                                                        cronjob.get("hour", "*"),
                                                        cronjob.get("dom", "*"),
                                                        cronjob.get("month", "*"),
                                                        cronjob.get("dow", "*")),
                                   comment))
            code, tags = self.d.menu("Here you can define times, when "
                                     "to run a backup.",
                                     choices=choices,
                                     backtitle=bt)
            
            if code == self.d.DIALOG_OK:
                if tags.startswith("Add"):
                    self.backup_add()
                else:
                    self.backup_delete(tags)
            else:
                break
        pass
    
    def backup_add(self):
        '''
        Add a backup date.
        '''
        bt = "Add a new backup date"
        code, bdate = self.d.inputbox("The date to run the backup. "
                                      "Please enter it like this: "
                                      "<Minute>  <Hour>  <Day-of-Month> "
                                      " <Month>  <Day-of-Week>. You may"
                                      " use '*' as wildcard entry.",
                                      width=70,
                                      backtitle=bt)
        
        if code == self.d.DIALOG_OK:
            date_fragments = bdate.split()
            if len(date_fragments) == 5:
                pass
            elif len(date_fragments) == 4:
                date_fragments.append('*')
            elif len(date_fragments) == 3:
                date_fragments.append('*')
                date_fragments.append('*')
            elif len(date_fragments) == 2:
                date_fragments.append('*')
                date_fragments.append('*')
                date_fragments.append('*')
            elif len(date_fragments) == 1:
                date_fragments.append('*')
                date_fragments.append('*')
                date_fragments.append('*')
                date_fragments.append('*')
            else:
                return
            self.Backup.add_backup_time(date_fragments)
    
    def backup_delete(self, tag):
        '''
        Delete a backup date
        '''
        bt = "Delete a backup date"
        (minute, hour, dom, month, dow) = tag.split()
        code = self.d.yesno("Do you want to delete the backup "
                            "job at time %s:%s. "
                            "Month:%s, Day of Month: %s, "
                            "Day of week: %s?" %
                            (hour, minute, month, dom, dow))
        if code == self.d.DIALOG_OK:
            # Delete backup job.
            self.Backup.del_backup_time(hour, minute, month, dom, dow)
            
    def backup_restore(self, tag):
        '''
        Restore a backup
        '''
        bt = "Restore a backup"
        code = self.d.yesno("Are you sure you want to restore the backup %s? "
                            "Current data will be lost. The restore will "
                            "restore the encryption key, administrator "
                            "settings, token database, audit log, RADIUS "
                            "clients, server certificates... " 
                            "If unsure, please "
                            "perform a backup before restoring the old one."
                            % tag,
                            width=70)
        if code == self.d.DIALOG_OK:
            # Restore the backup
            self.d.gauge_start("Restoring backup %s" % tag, percent=20)
            self.Backup.restore_backup(tag)
            self.d.gauge_update(percent=90)
            self.data_changed = True
            time.sleep(1)
            self.d.gauge_stop()
        
    def backup_now(self):
        '''
        Run the backup now.
        '''
        self.Backup.backup_now()
    
    def backup_view(self):
        '''
        View the saved backup files to restore one.
        '''        
        bt = "Restore a backup"
        while 1:
            backups = self.Backup.get_backups()
            choices = []
            for bfile in sorted(backups.keys(), reverse=True):
                choices.append((bfile, "%s %s" % (backups[bfile].get("size"),
                                                  backups[bfile].get("time"))))
            if len(choices) == 0:
                    self.d.msgbox("No backups found!")
                    break
            else:
                code, tags = self.d.menu("Choose a backup you wish to "
                                         "restore...",
                                         choices=choices,
                                         backtitle=bt,
                                         width=78)
                if code == self.d.DIALOG_OK:
                    self.backup_restore(tags)
                else:
                    break
        
    
    def webserver_menu(self):
        bt = "Webservice configuration"
        while 1:
            code, tags = self.d.menu("Configure Webserver",
                                     choices=[("enable or disable webserver", ""),
                                              ("nginx webservices", ""),
                                              ("create new certificates", ""),
                                              ("restart services", "")
                                         ],
                                     backtitle=bt)
            if code == self.d.DIALOG_OK:
                if tags.startswith("enable"):
                    self.webserver_enable()
                elif tags == "create new certificates":
                    self.webserver_certificate()
                elif tags.startswith("view"):
                    self.webserver_view()
                elif tags.startswith("nginx"):
                    self.webserver_services()
                elif tags.startswith("restart"):
                    self.webserver_restart()
            else:
                break
        
    def webserver_certificate(self):
        code = self.d.yesno("This will overwrite the existing "
                            "certificate. Create new?",
                            backtitle="Create webserver certificate",
                            defaultno=1)
        if code == self.d.DIALOG_OK:
            self.NginxConfig.create_certificates()
            self.data_changed = True
        
        
    def webserver_services(self):
        webservices = self.NginxConfig.get_webservices()
        code, tags = self.d.checklist("Enable nginx webservices. Only enable "
                                      "'privacyidea' unless you exactly know, "
                                      "what you are doing!",
                                      choices=webservices,
                                      backtitle="Enable webserives")
        if code == self.d.DIALOG_OK:
            self.NginxConfig.enable_webservice(tags)
            self.data_changed = True
            
    def webserver_restart(self):
        code = self.d.yesno("Do you want to restart the services for the "
                            "changes to take effect?")
        if code == self.d.DIALOG_OK:
            #self.d.gauge_start("Restarting uwsgi",
            #                   title="Restarting services")
            self.NginxConfig.restart("uwsgi")
            #self.d.gauge_update(50,
            #                    "Restarting nginx...",
            #                    update_text=True)
            self.NginxConfig.restart("nginx")
            #self.d.gauge_update(100,
            #                    "Restarted services",
            #                    update_text=True)
            #self.d.gauge_stop()
            self.data_changed = False
        
        
    def webserver_enable(self):
        nginx, uwsgi = self.NginxConfig.is_active()
        
        code, tags = self.d.radiolist("enable or disable the webservice", 
                                      choices=[("enable",
                                                "privacyIDEA "
                                                "will start automatically "
                                                "at boot time",
                                                int(nginx and uwsgi)),
                                               ("disable",
                                                "privacyIDEA "
                                                "will not start automatically.",
                                                int(not(nginx and uwsgi)))],
                                      width=70,
                                      backtitle="Enable or disable webservice")
        if code == self.d.DIALOG_OK:
            if tags == "enable":
                self.NginxConfig.enable()
                self.data_changed = True
            elif tags == "disable":
                self.NginxConfig.disable()
                self.data_changed = True
    
    def radius_menu(self):
        while 1:
            code, tags = self.d.menu("Configure FreeRADIUS",
                                     choices=[("view config",""),
                                              ("client config", ""),
                                              ("sites", "Enable and disable RADIUS" 
                                                        " sites")
                                         ])
            if code == self.d.DIALOG_OK:
                if tags.startswith("client"):
                    self.radius_clients()
                if tags.startswith("sites"):
                    self.radius_sites()
            else:
                break
    
    def radius_sites(self):
        sites = self.RadiusConfig.get_sites()
        code, tags = self.d.checklist("The FreeRADIUS sites you want to "
                                      "enable. You should only enable "
                                      "'privacyidea' unless you know "
                                      "exactly what you are doing!",
                                      choices=sites,
                                      backtitle="Enable sites")
        if code == self.d.DIALOG_OK:
            self.RadiusConfig.enable_sites(tags)    
    
    def radius_clients(self):
        while 1:
            clients = [("Add new client", "Add a new RADIUS client")]
            clients_from_file = self.RadiusConfig.clients_get()
            for client in clients_from_file.keys():
                clients.append( (client, "") )
            code, tags = self.d.menu("You can select an existing RADIUS client "
                                     "to either delete it or change it " 
                                     "or create a new client",
                                     choices=clients,
                                     backtitle="Manage RADIUS clients")
            
            if code == self.d.DIALOG_OK:
                if tags.startswith("Add new"):
                    self.radius_client_add()
                else:
                    self.radius_client_manage(tags)
            else:
                break

    def radius_client_add(self):
        bt="Add a new RADIUS client"
        code, clientname = self.d.inputbox("The name of the new client",
                                           backtitle=bt)
        if code != self.d.DIALOG_OK:
            return
        code, ip = self.d.inputbox("The IP address of the new client %s" %
                                   clientname,
                                   backtitle=bt)
        if code != self.d.DIALOG_OK:
            return
        code, netmask = self.d.inputbox("The netmask of the new client %s. "
                                        "The netmask should be in CIDR notation, "
                                        "i.e. use 24, NOT 255.255.255.0" %
                                        clientname,
                                        backtitle=bt)
        if code != self.d.DIALOG_OK:
            return
        code, secret = self.d.inputbox("The secret of the new client %s" %
                                       clientname,
                                       backtitle=bt)
        
        code, shortname = self.d.inputbox("The shortname of the new client %s" %
                                          clientname,
                                          backtitle=bt)
         
        if code == self.d.DIALOG_OK:
            client = {}
            if ip:
                client["ipaddr"] = ip
            if netmask:
                client["netmask"] = netmask
            if secret:
                client["secret"] = secret
            if shortname:
                client["shortname"] = shortname
            self.RadiusConfig.client_add({clientname: client})
            
    
    def radius_client_manage(self, clientname):
        bt="Manage client %s" % clientname
        code, tags = self.d.menu("Manage client %s" % clientname,
                                 choices=[("Delete client", "")],
                                 backtitle=bt)
        if code == self.d.DIALOG_OK:
            if tags.startswith("Delete"):
                self.d.yesno("Do you really want to delete the "
                             "RADIUS client %s?" % clientname)
                self.RadiusConfig.client_delete(clientname)
                


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)
       
    args = parser.parse_args()
    return args



def main():
    locale.setlocale(locale.LC_ALL, '')
    args = create_arguments()
    pS = pSetup(config=args.file)
    pS.main_menu()
    

if __name__ == '__main__':
    main()



