#!/usr/bin/env python
"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/toboso/etc/dist.py $
$Id: dist.py 26297 2005-03-07 19:40:42Z dbinger $

This is a script that attempts to install Toboso and related python
packages on a Unix-like system that already has python and apache
installed.  It would be wise to read this script before you run it,
and to run it as an ordinary user if possible.

This has only been tested on an OS X system with fink installations
of httpd and python2.3.
It attempts to set up apache to run toboso on
http://127.0.0.1:8000.

The site.conf file and the apache-global.conf file are probably
the first things you will want to edit after trying this script.
You should also inspect the permissions on the installation directory
tree created by this script to make sure that they make sense for your
system.

"""
from os import mkdir, getenv, chmod
from os.path import exists, join, dirname
from sys import exit, executable as python
import sys
from commands import getstatusoutput
from shutil import copyfile, rmtree, copytree
from urllib2 import urlopen

is_developer = getenv('USER') in ['dbinger']

def prompt(question, default):
    if is_developer:
        return default
    return raw_input('%s [%s] ' % (question, default)) or default

default_installation_directory = '/tmp/toboso'
installation_directory = prompt('Where can an installation directory be created? ',
                                default_installation_directory)
as_root = prompt(
    'What sudo-like command should be used to install python packages? ',
    'sudo')
httpd = prompt('Full path to httpd?', '/usr/sbin/httpd')

http_host_name = '127.0.0.1'
http_port = 8000
scgi_port = 1984
durus_port = 2001


if exists(installation_directory):
    if (is_developer and
        installation_directory == default_installation_directory):
        rmtree(installation_directory)
    else:
        print installation_directory, 'already exists.'
        exit(1)

mkdir(installation_directory)
src_directory = join(installation_directory, 'src')
mkdir(src_directory)

def run(command):
    status, output = getstatusoutput(command)
    if status != 0:
        print "FAIL: %r" % command
        print "STATUS=%s" % status
        print output
        exit(1)
    return "\n$ %s\n%s\n" % (command, output)

def get_dist(package_directory_name, package_title):
    tarball = join(src_directory, '%s.tar.gz' % package_title)
    if is_developer: 
        dev_dir = join(getenv('HOME'), 'src/mems/%s' % package_directory_name)
        run("cd %s; %s setup.py sdist" % (dev_dir, python))
        copyfile("%s/dist/%s.tar.gz" % (dev_dir, package_title), tarball)
    else:
        f = urlopen('http://www.mems-exchange.org/software/files/%s/%s.tar.gz '
                    % (package_directory_name, package_title))
        target = open(tarball, 'w')
        for chunk in f:
            target.write(chunk)
        f.close()
        target.close()
    run("tar --directory %s -xzf %s" % (src_directory, tarball))


def get_build_install(package_directory, package_title):
    get_dist(package_directory, package_title)
    package_directory = join(src_directory, package_title)
    run("cd %s; %s setup.py build" % (package_directory, python))
    print run("cd %s; %s %s setup.py install" % (
        package_directory, as_root, python))

TOBOSO = "Toboso-0.6"
SCGI = "scgi-1.2"
for package_directory, package_title in [
    ('quixote', 'Quixote-2.0a5'),
    ('dulcinea', 'Dulcinea-0.6'),
    ('durus', 'Durus-1.5'),
    ('toboso', TOBOSO),
    ('mod_scgi', SCGI),
    ('grouch', 'Grouch-0.4'),
    ('sancho', 'Sancho-2.0')]:
    get_build_install(package_directory, package_title)

def install_directory(name, mode=None):
    path = join(installation_directory, name)
    mkdir(path)
    if mode is not None:
        chmod(path, mode)
    return path

var_directory = install_directory('var')
log_directory = install_directory('logs', 0777)
toboso_log_directory = install_directory('logs/toboso')
conf_directory = install_directory('conf')
apache_directory = install_directory('conf/apache')
apache_pid = join(var_directory, 'apache.pid')

def write_apache_conf():
    f = open(join(apache_directory, 'apache-global.conf'), 'w')
    f.write('\n'.join([
        '#Include /etc/httpd/httpd.conf',
        'LoadModule scgi_module /usr/libexec/httpd/mod_scgi.so',
        'ServerRoot %s' % installation_directory]))
    f.close()

write_apache_conf()

sites_directory = install_directory('sites')
toboso_site = install_directory('sites/toboso')
copytree(join(src_directory, '%s/docroot' % TOBOSO),
         join(toboso_site, 'docroot'))

site_conf = join(conf_directory, 'site_config.py.orig')

def write_site_conf():
    f = open(site_conf, 'w')
    f.write('\n'.join([
        'toboso=dict('
        '  apache_version=1,',
        '  httpd="%s",' % httpd,
        '  administrator="You <webmaster@example.org>",',
        '  allow_anonymous_registration=True,',
        '  conf_directory="%s",' % conf_directory,
        '  var_directory="%s",' % var_directory,
        '  log_directory="%s",' % log_directory,
        '  sites_directory="%s",' % sites_directory,
        '  start_script_directory="%s",' % dirname(python),
        '  daemon_uid="%s",' % getenv('USER'),
        '  servername="%s",' % http_host_name,
        '  # comment out the next line if apache should not be started.',
        '  http_address="%s:%s",' % (http_host_name, http_port),
        '  #https_address="0:443",',
        '  scgi_address="%s:%s",' % ('localhost', scgi_port),
        '  durus_address="%s:%s",' % ('localhost', durus_port),
        '  root_directory="toboso.ui.qslash.TobosoDirectory",',
        '  root_exports=%s,' % (
        ['', 'css', 'user', 'admin', 'login', 'logout', 'my']),
        '  cache_size=5000)',
        'config={"toboso" : toboso}'
        ]))

write_site_conf()

site_conf_installed = None
for path in sys.path:
    if path.endswith('site-packages'):
        site_conf_installed = join(path, 'site_config.py')
        print run("%s cp %s %s" % (
            as_root, site_conf, site_conf_installed))

print run("%s %s/%s/bin/create_db.py" % (python, src_directory, TOBOSO))

print "This script does not install the mod_scgi apache module."
print "You need to do that yourself."
print "You'll find instructions in %s/apache*/README" % (
    join(src_directory, SCGI))
print

print "Customize config by editing %r." % site_conf_installed


