########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Server/Client/Commands/Create/Server.py,v 1.2 2004/11/08 16:34:17 uogbuji Exp $
"""
Implementation of '4ss create server' 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 Server definiiton resource in a 4Suite \
repository. If necessary, you will be prompted first \
for credentials and access info to connect to the repository."""


import sys, sha, getpass
import posixpath
from Ft.Server.Client import FtServerClientException
from Ft.Lib import Uri
from Ft.Server.Common import ResourceTypes, AclConstants
from Ft.Server.Client import Core
from Ft.Server.Client import SmartLogin
from Ft.Server.Client.Commands import CommandUtil


def Run(options, args):
    print "Only HTTP servers are supported now.  This will create an HTTP (Web) server."
    print "At the following prompts, just hit enter if the given defaults are OK."
    server_file = raw_input("Path of the server file to create [/web/server.xml]: ")
    if not server_file: server_file = '/web/server.xml'
    server_port = raw_input("Port on which to listen for HTTP requests [8080]: ")
    if not server_port: server_port = '8080'
    server_name = raw_input("Brief name to identify the server [web-server]: ")
    if not server_name: server_name = 'web-server'
    contact = raw_input("Contact e-mail address to display in case of error [admin@localhost]: ")
    if not contact: contact = 'admin@localhost'
    server_doc = SERVER_FILE%locals()

    repo = CommandUtil.GetRepository(options, '4ss.create.server')
    if repo is not None:
        commit = False
        try:
            container = posixpath.split(server_file)[0]
            if repo.hasResource(container):
                cont = repo.fetchResource(container)
            else:
                cont = repo.createContainer(container, 1)
            if cont.isResourceType(ResourceTypes.ResourceType.CONTAINER):
                cont.setAcl(AclConstants.WRITE_ACCESS,
                    AclConstants.USERS_GROUP_NAME, AclConstants.ALLOWED)
                cont.setAcl(AclConstants.READ_ACCESS,
                    AclConstants.USERS_GROUP_NAME, AclConstants.ALLOWED)
                cont.setAcl(AclConstants.READ_ACCESS,
                    AclConstants.WORLD_GROUP_NAME, AclConstants.ALLOWED)
                doc = repo.createDocument(
                    server_file, server_doc, imt='text/xml', docDef=None,
                    forcedType=ResourceTypes.ResourceType.SERVER)
                commit = True
                print "Server created.  You may need to restart the 4Suite repository in order to properly launch the new server."
                #print "You can test the server by browsing http://[hostname]:%s/?xslt=container.xslt"%server_port
            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


SERVER_FILE = """\
<Server xmlns="http://xmlns.4suite.org/reserved"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
>
  <dc:Description>Scratch server</dc:Description>
  <Status running='1'/>
  <Module>Http</Module>
  <Handler>http_basic</Handler>
  <Port>%(server_port)s</Port>

  <!-- contact information -->
  <ServerAdmin>%(contact)s</ServerAdmin>
  <ServerName>%(server_name)s</ServerName>

  <!-- Provide a sensible rendering default for containers -->
  <DefaultXslt type='#container'>/ftss/data/container.xslt</DefaultXslt>

  <!-- logging -->
  <LogLevel>notice</LogLevel>

  <DocumentRoot>/</DocumentRoot>
</Server>
"""


def Register():
    from Ft.Lib.CommandLine import Options, Command, Arguments
    cmd = Command.Command('server',
                          'Create a new server definition in a 4Suite repository',
                          '/documents',
                          __doc__,
                          function=Run,
                          arguments=[],
                          options=Options.Options([]),
                          fileName=__file__,
                          )
    return cmd

