BASE_CONTAINER = '/export'
import test_prime, os, tempfile
from Ft.Lib.CommandLine import CommandLineTestUtil

import Server
import test_install
#from distutils import dir_util

from Server.Client.Core import test_helper
from Ft.Server.Common import ResourceTypes, AclConstants

def Init(repo):
    if repo.hasResource(BASE_CONTAINER):
        repo.deleteResource(BASE_CONTAINER)

    test_prime.CreateCommand(repo, ['4ss', 'install'])

    #Make sure that the install stuff is not previously installed
    #this messes up our users
    if repo.hasResource(test_install.BASE_CONTAINER):
        repo.deleteResource(test_install.BASE_CONTAINER)




def Test(tester):

    #First add a bunch of stuff to the repo, then export it and make
    #sure it is correct
    #Then, blow it away, and reinstall as a last step of verification

    test_prime.InitRepo(tester, Init, ['4ss', 'export'])

    InitialInstall(tester)
    Export(tester)
    try:
        TestFiles(tester)
        ReInit(tester)
        ReInstall(tester)
        ReTest(tester)
    finally:
##        if tempdir:
#3            dir_util.remove_tree(tempdir)
        pass

def InitialInstall(tester):

    #Use complex.xml as an install
    setupFile = os.path.join(os.path.dirname(Server.__file__), 'Common', 'Install', 'complex.xml')

    baseConfig = {'host':tester.test_data['ftrpc-host'],
                  'port':tester.test_data['ftrpc-port'],
                  'username':tester.test_data['userName'],
                  'password':tester.test_data['password'],
                  }

    cfg = baseConfig.copy()
    cfg['base'] = BASE_CONTAINER
    tr1 = CommandLineTestUtil.TestRun('Install', cfg, [setupFile],
                                      skipOutputTest=True)

    t = CommandLineTestUtil.Test('4ss install', [tr1])

    return t.test(tester)

tempdir = None
def Export(tester):

    setupFile = os.path.join(os.path.dirname(Server.__file__), 'Common', 'Install', 'complex.xml')

    baseConfig = {'host':tester.test_data['ftrpc-host'],
                  'port':tester.test_data['ftrpc-port'],
                  'username':tester.test_data['userName'],
                  'password':tester.test_data['password'],
                  }

    global tempdir
    tempdir = tempfile.mktemp()
    os.mkdir(tempdir)

    cfg = baseConfig.copy()
    cfg['directory'] = tempdir
    tr1 = CommandLineTestUtil.TestRun('Export', cfg, [BASE_CONTAINER],
                                      skipOutputTest=True)

    t = CommandLineTestUtil.Test('4ss export', [tr1])

    return t.test(tester)


def TestFiles(tester):
    tester.startGroup("Test outputed files")
    for d in ['export',
              'export/cont',
              'export/cont/sub',
              'export/perm']:
        p = os.path.join(tempdir, d)
        tester.startTest(p)
        tester.compare(1, os.path.isdir(p))
        tester.testDone()

    for f in ['export/test1.html',
              'export/test2.html',
              'export/test3.html',
              'export/perm/test-user',
              'export/perm/test-user2',
              'export/perm/test-group',
              'export/test1.xml',
              'export/test1.xpathdd',
              'export/test1.alias',
              'export/test1.aliasref',
              'export/test-include.xslt',
              'export/test-import.xslt',
              'export/test1.xslt',
              'export/test2.alias',
              ]:
        p = os.path.join(tempdir, f)
        tester.startTest(p)
        tester.compare(1, os.path.isfile(p))
        tester.testDone()


    tester.groupDone()


def ReInit(tester):

    #Remove the export directory
    tester.startTest("Remove the installation directory")
    repo = test_helper.GetRepo(tester)
    repo.deleteResource(BASE_CONTAINER)
    repo.txCommit()
    tester.testDone()

def ReInstall(tester):

    #Use complex.xml as an install
    setupFile = os.path.join(tempdir, 'export', 'setup.xml')

    baseConfig = {'host':tester.test_data['ftrpc-host'],
                  'port':tester.test_data['ftrpc-port'],
                  'username':tester.test_data['userName'],
                  'password':tester.test_data['password'],
                  }

    cfg = baseConfig.copy()
    #cfg['base'] = BASE_CONTAINER
    tr1 = CommandLineTestUtil.TestRun('Re-Install', cfg, [setupFile],
                                      skipOutputTest=True)

    t = CommandLineTestUtil.Test('4ss install', [tr1])

    return t.test(tester)


def ReTest(tester):

    #Test that everything was added properly into the DB
    tester.startGroup("Verify that all was readded")
    repo = test_helper.GetRepo(tester)
    #Test the containers
    for d in ['export',
              'export/cont',
              'export/cont/sub',
              'export/perm']:
        tester.startTest(d)
        tester.compare(1, repo.hasResource(d))
        res = repo.fetchResource(d)
        tester.compare(ResourceTypes.ResourceType.CONTAINER, res.resourceType)
        tester.testDone()

    from Server.Common import Install
    base = os.path.dirname(Install.__file__)

    #Test the HTML files
    f = open(os.path.join(base, 'test1.html'), 'rb')
    src = f.read()
    f.close()
    for filename, imt in (('test1.html', 'text/html'),
                          ('test2.html', 'text/text'),
                          ('test3.html', 'text/plain'),
                          ('test1.aliasref', 'text/plain'),
                         ):
        tester.startTest(filename)
        repopath = 'export/' + filename
        tester.compare(ResourceTypes.ResourceType.RAW_FILE, repo.hasResource(repopath))
        res = repo.fetchResource(repopath)
        tester.compare(ResourceTypes.ResourceType.RAW_FILE, res.resourceType)
        tester.compare(imt, res.getImt())
        tester.compare(src, res.getContent())
        tester.testDone()

    #Test the permissions on the container
    tester.startTest("Permissions")
    res = repo.fetchResource('/export/perm')
    acl = res.getAcl()
    tester.compare(1, acl.has_key(AclConstants.READ_ACCESS))
    tester.compare(1, acl[AclConstants.READ_ACCESS].has_key('test-user'))
    tester.compare(AclConstants.ALLOWED, acl[AclConstants.READ_ACCESS]['test-user'])
    tester.compare(1, acl[AclConstants.READ_ACCESS].has_key('test-group'))
    tester.compare(AclConstants.ALLOWED, acl[AclConstants.READ_ACCESS]['test-group'])
    tester.compare('test-user2', res.getOwner().getUsername())
    tester.testDone()

    tester.startTest("Group Membership")
    res = repo.fetchResource('/export/perm/test-group')
    members = res.getMembers()
    tester.compare(1, len(members))
    member = members [0]
    tester.compare('test-user', member.getUsername())
    tester.testDone()

    #test the users
    tester.startTest("Users")
    tester.compare(ResourceTypes.ResourceType.USER, repo.hasResource('/export/perm/test-user'))
    tester.compare(ResourceTypes.ResourceType.USER, repo.hasResource('/export/perm/test-user2'))
    tester.testDone()

    #Test the doc defs
    tester.startTest("Doc Defs")
    tester.compare(ResourceTypes.ResourceType.XPATH_DOCUMENT_DEFINITION,
                   repo.hasResource('/export/test1.xpathdd'))
    res = repo.fetchResource('/export/test1.xpathdd')
    f = open(os.path.join(base, 'test1.xpathdd'), 'rb')
    src = f.read()
    f.close()
    tester.compare(src, res.getContent())

    tester.compare(ResourceTypes.ResourceType.XML_DOCUMENT,
                   repo.hasResource('/export/test1.xml'))
    res = repo.fetchResource('/export/test1.xml')
    f = open(os.path.join(base, 'test1.xml'), 'rb')
    src = f.read()
    f.close()
    tester.compare(src, res.getContent())
    tester.compare('/export/test1.xpathdd', res.getDocumentDefinition().getAbsolutePath())

    tester.testDone()

    tester.startTest("alias")
    tester.compare(ResourceTypes.ResourceType.ALIAS,
                   repo.hasResource('/export/test1.alias;no-traverse'))
    res = repo.fetchResource('/export/test1.alias;no-traverse')
    tester.compare('/export/test1.aliasref', res.getReference().getAbsolutePath())

    tester.testDone()

    #Test the XSLT files
    for filename in ('test1.xslt', 'test-include.xslt', 'test-import.xslt'):
        tester.startTest(filename)
        repopath = 'export/' + filename
        f = open(os.path.join(base, filename), 'rb')
        src = f.read()
        f.close()
        tester.compare(ResourceTypes.ResourceType.XSLT_DOCUMENT, repo.hasResource(repopath))
        res = repo.fetchResource(repopath)
        tester.compare(src, res.getContent())
        tester.testDone()

    tester.startTest("external alias")
    tester.compare(ResourceTypes.ResourceType.ALIAS,
                   repo.hasResource('/export/test2.alias;no-traverse'))
    res = repo.fetchResource('/export/test2.alias;no-traverse')
    tester.compare('/ftss/users', res.getReference().getAbsolutePath())

    tester.testDone()

    repo.txRollback()
    tester.groupDone()

