########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Client/Commands/Agent.py,v 1.15 2004/10/19 13:32:31 uogbuji Exp $
"""
Implementation of '4ss agent' 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 will set a default username, password hash, \
hostname and port in an environment variable in a new shell so that you \
do not need to provide this info for subsequent invocations of 4ss \
command-line scripts. The username and password must be valid for the \
repository server on the given host and port. This command is an \
alternative to the login command."""

import os, sys

from Ft.Server.Client import Core, FtServerClientException
from Ft.Server.Common import ClAuthenticate

AGENT_ENV_VAR = 'FTSS_AGENT'


def TextAgent(options, args):

    userName = ClAuthenticate.GetUserName(
        prompt='Default username for auto-logins in the new session: ', emptyOK=False)

    passwd = ClAuthenticate.GetPass('Password for %s: ' % userName)
    passwdHash = ClAuthenticate.HashPasswd(passwd)

    host = ClAuthenticate.GetHostName('Default host for auto-logins in the new session <%s>: ' % Core.FTRPC_HOST)
    host = host or Core.FTRPC_HOST
    port = ClAuthenticate.GetPort('Default port for auto-logins in the new session <%i>: ' % Core.FTRPC_PORT)
    try:
        port = int(port or Core.FTRPC_PORT)
    except ValueError:
        raise ValueError('Invalid port %r' % port)

    sys.stderr.write('Verifying login...')
    sys.stderr.flush()

    repo = Core.GetRepository(userName, passwdHash, host, port)
    if repo is None:
        sys.stderr.write('Failed.\n%s\n' % str(e))
        sys.stderr.flush()
        return
    else:
        sys.stderr.write('Success!\n')
        sys.stderr.flush()
        try:
            repo.txRollback()
        except:
            pass

    os.environ[AGENT_ENV_VAR] = repr((userName, passwdHash, host, port))

    shell = args.get('shell')
    if not shell:
        shell = os.environ.get('SHELL')
    if not shell:
        shell = os.environ.get('shell')

    if not shell and os.name == 'posix':
        shell = '/bin/sh'
    elif not shell:
        shell = os.environ.get('COMSPEC')
        if not shell:
            shell = 'COMMAND.COM'

    print "Starting new shell: %s" % shell
    os.system(shell)
    return


def Register():
    from Ft.Lib.CommandLine import Options, Command, Arguments
    cmd = Command.Command('agent',
                          'Spawn a subshell that knows authentication defaults',
                          '',
                          __doc__,
                          function = TextAgent,
                          arguments = [Arguments.OptionalArgument('shell',
                                                                  'name of shell to execute (default is system specific)',
                                                                  str),
                                       ],

                          fileName = __file__,
                          )
    return cmd
