from __future__ import with_statement

import subprocess, os, sys, tempfile, shutil

def bootstrap(project, package, quiet, username, elmname, password,
              bazkitype, extra_db, custom_db, remove_db, admin_path,
              urlprefix, repo=None):
    """Create a bazsvn repository in the current directory (or use the
    specified repo), and bootstrap the database using a subversion import."""

    res = os.system('./clear-database.py')
    if res != 0:
        print >>sys.stderr,'clear-database failed: %d!'%res
        sys.exit(res)

    # cwd is the new quickstarted tree
    if repo is None:
        subprocess.check_call(['svnadmin', 'create', 'repository'])
        repo = 'repository'

    os.symlink('../../precommit.py',
                os.path.join(repo, 'hooks', 'pre-commit'))

    tempd = tempfile.mkdtemp('.%s.bazstart'%project)
    shutil.copytree(
        os.path.join(os.path.dirname(__file__),
                     'initial_db'),
        os.path.join(tempd,'initial_db'))
    for r in remove_db:
        shutil.rmtree(os.path.join(tempd,'initial_db',r))
    for db in (extra_db, custom_db):
        if db:
            cmd = ['rsync','-a',
                   db+'/',
                   os.path.join(tempd, 'initial_db')+'/']
            assert subprocess.call(cmd) == 0, cmd
    # This is pretty hardcoded; should I treat initial_db as a paste template
    # instead? Probably.
    # This if is a hack for a test.
    if urlprefix:
        with open(os.path.join(tempd,'initial_db',admin_path,
                               elmname+'.yaml'),
                  'w') as admin:
            print >>admin,'comment: Initial admin user, created by bazstart.'
            print >>admin,'username: %s' % username
            print >>admin,'password: %s' % password
            print >>admin,'name: %s' % elmname

        with open(os.path.join(tempd, 'initial_db/Object/Config',
                               'UrlConfig.yaml'), 'w') as urlconfig:
            print >>urlconfig, """comment: |
  Configuration used when generating link URLs.  Note that if xhrprefix is
  different from prefix, it must be a subdomain of prefix and you must add
  
  {{{
  Header set Access-Control-Allow-Origin <prefix>
  Header set Access-Control-Allow-Credentials true
  }}}

  to ##webroot/.htaccess##.  xhrprefix (but not the others) may contain a
  *, which will be replaced by an arbitrary string to spread out different
  XHRs to different domains so more things can load in parallel."""
            print >>urlconfig, "prefix: %s" % urlprefix
            print >>urlconfig, "imageprefix: %s" % urlprefix
            print >>urlconfig, "xhrprefix: %s" % urlprefix
            print >>urlconfig, "svnprefix: %s" % urlprefix.replace('http://',
                                                                   'svn://')
        
        for path in os.listdir(os.path.join(tempd, 'initial_db/bin/')):
            path = os.path.join(tempd, 'initial_db/bin/', path)
            with open(path) as fil:
                old = fil.read()
            new = old.replace('{{project}}', project)
            new = new.replace('{{bazkitype}}', bazkitype)
            with open(path, 'w') as fil:
                fil.write(new)
            

    import_cmd = ['svn', 'import', '--username', 'bazki', '-m',
                  'Bootstrapping ' + bazkitype.capitalize()
                  + ' contents on project ' + project + ' creation.',
                  os.path.join(tempd, 'initial_db'),
                  'file://' + os.path.abspath(repo)]
    kw = {}
    if quiet:
        kw['stdout'] = subprocess.PIPE
        kw['stderr'] = subprocess.PIPE
    process = subprocess.Popen(import_cmd, **kw)
    out, err = process.communicate()
    if process.returncode != 0:
        if quiet:
            print >>sys.stderr, err
        print >>sys.stderr, ("SVN import failed with status %d"
                             % process.returncode)
        sys.exit(process.returncode)

    os.unlink('clear-database.py')
    shutil.rmtree(tempd)
