########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Client/Commands/Create/User.py,v 1.12 2004/09/26 22:21:19 mbrown Exp $
"""
Implementation of '4ss create user' command
(functions defined here are used by the Ft.Lib.CommandLine framework)

Copyright 2004 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

__doc__ = """This command creates a new User resource in the 4Suite \
repository. It will first prompt for a password for the new User. Then \
it will attempt to connect to the repository to create the user, \
prompting first for credentials and access info if necessary. \
The user accessing the repository must have sufficient permissions in \
order to create the new User, and the new User must not already exist."""

import sys

from Ft.Server.Client.Commands import CommandUtil
from Ft.Server.Common import ResourceTypes, AclConstants
from Ft.Server.Common import ClAuthenticate


def Run(options,args):

    username = args['userName']

    while True:
        passwd = ClAuthenticate.GetPass('New password for %s: ' % username)
        passwd2 = ClAuthenticate.GetPass('Re-enter password to confirm: ')
        if passwd == passwd2:
            break
        else:
            sys.stderr.write('Passwords did not match. Please try again.\n')
            sys.stderr.flush()

    passwdHash = ClAuthenticate.HashPasswd(passwd)

    repo = CommandUtil.GetRepository(options,'4ss.create.user')
    if repo is not None:
        commit = False
        if options.has_key('container'):
            containerPath = options['container']
        else:
            containerPath = '/ftss/users'
        try:
            container = repo.fetchResource(containerPath)
            if container.isResourceType(ResourceTypes.ResourceType.CONTAINER):
                user = container.createUser(username, passwdHash)
                #If the user does not own the user resource, can't
                #change passwords, etc.
                user.setOwner(user)
                user.setAcl(AclConstants.READ_ACCESS,
                            AclConstants.WORLD_GROUP_NAME,
                            AclConstants.ALLOWED)
                commit = True
            else:
                sys.stderr.write("The resource '%s' is not a container.\n" % container.getPath())
                sys.stderr.flush()
        finally:
            try:
                if commit:
                    repo.txCommit()
                else:
                    repo.txRollback()
            except:
                pass
    return


def Register():

    from Ft.Lib.CommandLine import Options, Command, Arguments

    # just for help message
    defaultContainer = '/ftss/users'

    cmd = Command.Command('user',
                          'Create a new User and sets its password in a repository',
                          'michael',
                          __doc__,
                          function = Run,
                          arguments = [Arguments.RequiredArgument('userName',
                                                                  'The name of the user to create.',
                                                                  str),
                                       ],
                          options = Options.Options([Options.Option('c',
                                                                    'container=PATH',
                                                                    'The container in which to create the user (default: \'%s\')' % defaultContainer),
                                                    ]),
                          fileName = __file__,
                          heading = """\nNote: After entering the new user's password, you might be prompted for a user name. This is the user name of an existing user in 4SS with permissions to create a new user.\n""",
                          )
    return cmd

