#!/usr/bin/env python2.4

"""
create_project.py (a simple script for creating lots of projects)
Copyright (C) 2006 Yoan Blanc

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
"""

import os
import sys

__author__ = 'Yoan Blanc <yoan @ electronlibre.ch>'
__revision__ = '20061022'

""" Config """
__home = '/home/%s/projects' % os.getlogin()
__templates_path = '/usr/share/trac/templates'
__apache_conf = 'apache.conf'
__htpasswd = '.htpasswd'
__dirs = ('trac', 'svn', 'www', 'build', 'log')

def main(argv):
	"""
	Initiate a new project
	"""
	
	if(len(argv) < 3):
		print 'usage: %s <project_name> <project_port>' % argv[0]
		return
		
	project = argv[1]
	port = int(argv[2])
	root = os.path.join(__home, project) 
	htpasswd = os.path.join(__home, __htpasswd)

	os.mkdir(root)
	
	# directories (do not create the trac dir, created by trac-admin)
	print '[Creating the directory structure]'
	
	for d in __dirs[1:]:
		os.mkdir(os.path.join(root, d))
	
	print '[Apache configuration file]'
	
	conf = open(os.path.join(root, __apache_conf), 'w')
	conf.write("""#Apache Configuration for %(project)s
# Generated by create_project.py

# Port
Listen %(port)d

NameVirtualHost *:%(port)d

# VirtualHost
<VirtualHost *:%(port)d>
		DocumentRoot %(root)s/www
		ServerName %(project)s.work.electronlibre.com
	CustomLog %(root)s/log/access.log common
	CustomLog %(root)s/log/referer.log "%%{Referer}i -> %%U"
	CustomLog %(root)s/log/useragent.log "%%{User-agent}i"
	ErrorLog %(root)s/log/error.log
	LogLevel warn
		<Directory %(root)s/www>
				AddDefaultCharset Off
				Options Indexes FollowSymLinks
				AllowOverride All
		</Directory>
</VirtualHost>

# SVN
<Location /svn/%(project)s>
   DAV svn
   SVNPath %(root)s/svn/
   # Auth
   AuthType Basic
   AuthName "Subversion of %(project)s"
   AuthUserFile %(htpasswd)s
   Require  valid-user
</Location>

# Trac (via mod_python)
<Location /trac/%(project)s>
   SetHandler mod_python
   PythonHandler trac.web.modpython_frontend
   PythonOption TracEnv %(root)s/trac
   PythonOption TracUriRoot /trac/%(project)s
</Location>

# Auth
<Location /trac/%(project)s/login>
   AuthType Basic
   AuthName "Trac Project: %(project)s"
   AuthUserFile %(htpasswd)s
   Require valid-user
</Location>
""" % {'port': port, 'project':project, 'root':root, 'htpasswd':htpasswd})
	conf.close()
	
	# Subversion
	print '[Subversion]'
	
	os.system('svnadmin create %s' % (os.path.join(root, __dirs[1]),))
	
	print '   [Initial import]'
	
	tmp_dir = os.path.join(root, '.tmp')
	svn_dirs = ('tags', 'branches', 'trunk')
	
	for d in svn_dirs:
		os.makedirs(os.path.join(tmp_dir, d))
	
	os.system('svn import %s file://%s --message "Initial import" > /dev/null 2>&1' % (tmp_dir, os.path.join(root, __dirs[1])))
	
	for d in svn_dirs:
		os.removedirs(os.path.join(tmp_dir, d))
	
	for d in ('db', 'dav'):
		os.system('chmod -R a+w %s' % (os.path.join(root, __dirs[1], d))) 
	
	# Trac
	print '[Trac]'
	
	os.system('trac-admin %s initenv %s %s %s %s > /dev/null 2>&1' % (
	os.path.join(root, __dirs[0]),	# </path/to/projenv>
	project,			# <projectname>
	'sqlite:db/trac.db',		# <db>
	os.path.join(root, __dirs[1]),	# <repospath>
	__templates_path))		# <templatepath>
	# everybody right to write the db file (for Apache)
	os.chmod(os.path.join(root, __dirs[0], 'db'), 0777)
	os.chmod(os.path.join(root, __dirs[0], 'db', 'trac.db'), 0777)
	os.chmod(os.path.join(root, __dirs[0], 'attachments'), 0777)
	
	print '  [Setting the rights for Trac]'
	
	anon_rights = ('BROWSER_VIEW', 'CHANGESET_VIEW', 'FILE_VIEW', 'LOG_VIEW', 'MILESTONE_VIEW', 'REPORT_SQL_VIEW', 'REPORT_VIEW', 'ROADMAP_VIEW', 'SEARCH_VIEW', 'TICKET_CREATE', 'TICKET_MODIFY', 'TICKET_VIEW', 'TIMELINE_VIEW', 'WIKI_CREATE', 'WIKI_MODIFY', 'WIKI_VIEW')
	for right in anon_rights:
		os.system('trac-admin %s permission remove anonymous %s' % (os.path.join(root, __dirs[0]), right))
		os.system('trac-admin %s permission add authenticated %s' % (os.path.join(root, __dirs[0]), right))
	
	print ""
	print "[!!!] Need to link the conf file into Apache site-enabled directory:"
	print "sudo ln -s %s /etc/apache2/sites-enabled/%s" % (os.path.join(root, __apache_conf), project)
	print "\n[!!!] Check if you need a MySQL database (insert a password)"
	print """mysql -u root -p -e "CREATE DATABASE %s;" """ % project
	print """mysql -u root -p -e "GRANT ALL PRIVILEGES ON %s.* to '%s'@'localhost' IDENTIFIED BY 'password';" """ % (project, project)

if __name__ == "__main__" : main(sys.argv)
