#!/bin/bash

CMD=`basename $0`

# get library functions
#
export TOOLKIT="::env.TOOLKIT::"
. /lib/ku-base/libfiles.sh

usage()
{
	echo "
usage:	$CMD [options] projectname [bzr-url]
	$CMD --list

options:
 -l|--list	list all defined projects in kusa database
 -v|--verbose	be verbose
 -q|--quiet	be quiet
 -D|--debug	debug mode
" >&2
	exit 1
}

do_long_listing()
{
	local prj
	local fmt="%-16.16s %-30.30s %-30.30s\n"
	local fmt_h="%-16.16s %-30.30s %-30.30s\n"
	local line="----------------------------------------------------------------------"
	local bzrurl=
	local prjname=
	local desc=
	local wdir=
	local trac_datadir=`kusa-conf trac-server.datadir`	|| exit $?

	printf "$fmt_h" "PROJECT" "BZR-URL" "DESC"
	printf "$fmt_h" "$line" "$line" "$line"

	for prj in `kusa-conf --list trac.`
	do
		prjname=`echo $prj | sed -e 's/^trac\.//'`
		desc=`kusa-conf $prj.desc 2>/dev/null`
		wdir=$trac_datadir/cache/$prjname

		if [ -f $wdir/.bzr/branch/branch.conf ]
		then
			bzrurl=`grep "bound_location" $wdir/.bzr/branch/branch.conf | \
				sed -e 's/.*= *//'`
		else
			bzrurl="warn: checkout not yet done"
		fi
		printf "$fmt" "$prjname" "$bzrurl" "$desc"
	done
	echo
	return 0
}


# (MAIN)

prjname=
prjpath=
bzrurl=
do_list=false
VERBOSE=true
DEBUG=false

while [ $# != 0 ]
do
	case $1 in
	  -l|--list)	do_list=true ;;
	  -v|--verbose)	VERBOSE=true ;;
	  -q|--quiet)	VERBOSE=false ;;
	  -D|--debug)	DEBUG=true ;;
	  --)		break ;;
	  -*|"")	usage ;;
	  *)		break ;;
	esac
	shift
done

$do_list && {
	if $VERBOSE
	then
		do_long_listing
	else
		kusa-conf --list trac. | sed -e 's/^trac\.//'
	fi
	exit 0
}

[ $# -lt 1 ] && usage

prjname="$1"
bzrurl="$2"

conf="trac.$prjname"
errfile=/tmp/$CMD-$$.err
tmpconf=/tmp/$CMD-$$.conf

# sanity checks
#
[ "`id -u`" != 0 ] && {
	echo "error: this command must be run by 'root' user only" >&2
	exit 1
}
kusa-conf --listvars $conf >/dev/null || {
	echo "error: section [$conf] not found in kusa db" >&2
	exit 1
}


# get needed trac-server vars
#
trac_datadir=`kusa-conf trac-server.datadir`	|| exit $?
trac_usrgrp=`kusa-conf trac-server.user-group`	|| exit $?

# get project trac (repos) infos from kusa database
# and fill up temp config file $tmpconf; the file will
# be parsed, so the entries will be translated from instance
# specific (like trac.NAME) into temp vars, used in
# templates
#
prjdesc=`kusa-conf $conf.desc`			|| exit $?

# bzrurl, try to get from kusa db if not provided as arg
#
[ "$bzrurl" == "" ] && bzrurl=`kusa-conf $conf.bzr_url 2>/dev/null`

trac_prj_envdir="$trac_datadir/env/$prjname"
trac_prj_bzrdir="$trac_datadir/cache/$prjname"

# project desc, override from local if exists
#
[ -f $trac_prj_bzrdir/etc/desc ] && prjdesc=`cat $trac_prj_bzrdir/etc/desc`

# summary
#
echo "
  project:  $prjname
  desc:     $prjdesc
  bzrurl:   $bzrurl
  envdir:   $trac_prj_envdir
  bzrdir:   $trac_prj_bzrdir
"

# check for bzrdir
#
[ -d $trac_prj_bzrdir/.bzr ] || {
	echo "  bzr checkout dir '$trac_prj_bzrdir' not exists"

	if [ X"$bzrurl" != X"" ]
	then
		echo -e "  performing initial checkout from $bzrurl ...\n"
		bzr checkout $bzrurl $trac_prj_bzrdir || exit $?
		echo -e "  done"
	else
		echo "error: you must provide the bzr-url to perform the initial checkout"
		exit 1
	fi
}

cp /dev/null $tmpconf
cp /dev/null $tmpconf.2
chmod 600 $tmpconf $tmpconf.2	# be sure that nobody can read them

cat <<@EOF@ >>$tmpconf.2
[tmp]
  prjname	$prjname
  prjdesc	$prjdesc
  logname	$LOGNAME
  trac_envdir	$trac_prj_envdir
  bzrdir	$trac_prj_bzrdir

  location	\::$conf.site_prefix\::$prjname
  allow		\::$conf.allow\::

  ldap_url	\::$conf.ldap_url\::
  ldap_user	\::$conf.ldap_user\::
  ldap_password	\::$conf.ldap_password\::

  company_name	\::$conf.company_name\::	#alt 
  company_url	\::$conf.company_url\::		#link
  company_logo	\::$conf.company_logo\::	#src
  email		\::$conf.email\::		#smtp_from
  smtp_server 	\::$conf.smtp_server\::		#smtp_server

  today		`date`
  command	$CMD
@EOF@

$DEBUG && { echo "tmpconf.2:"; cat $tmpconf.2; }

kusa-conf-parse $tmpconf.2 > $tmpconf || exit $?
rm -f $tmpconf.2



# use trac-admin to create environment, if needed
#
input="$prjname
sqlite:db/trac.db
bzr
$trac_prj_bzrdir"

[ -d $trac_prj_envdir/conf ] || {
	jtmkpath $trac_prj_envdir $trac_usrgrp 0770	|| exit $?
	echo -en "  creating environment (trac-admin initenv) ... "
	echo "$input" | trac-admin $trac_prj_envdir initenv >$errfile 2>&1 || {
		status=$?
		echo "FAILED!"
		cat $errfile
		rm -f $errfile
		exit $status
	}
	echo "done"
	rm -f $errfile
}


# update config file
#
outfile="$trac_prj_envdir/conf/trac.ini"

[ -f $outfile ] && {
	# was the ini file customized?
	#
	if grep -q 'REMOVE THIS LINE IF YOU EDIT THIS FILE' $outfile
	then
		savefile="$outfile.`date '+%Y%d%m-%H%M'`"
		echo "  saving trac config file in $savefile"
		mv $outfile $savefile || exit $?
	else
		echo "  DON'T update trac config file (customized)"
	fi
}

[ -f $outfile ] || {
	tmpfile=/tmp/trac-$prjname.ini
	template=`ku_get_template trac.ini`				|| exit $?

	echo "  creating/updating trac environment configuration file"
	kusa-conf-parse --include $tmpconf $template >$tmpfile		|| exit $?
	mv $tmpfile $outfile						|| exit $?
}


# create default htpasswd file if needed
#
outfile="$trac_prj_envdir/htpasswd"
[ -f $outfile ] || {
	echo "  creating $outfile with default 'admin/admin' entry"
	echo "  (you still need to manually setup permissions using Admin module)"
	htpasswd -b -c $outfile admin admin
}


# perms
#
echo -n "  fixing perms ... "
chown -R $trac_usrgrp $trac_prj_envdir $trac_prj_bzrdir		|| exit $?
chmod -R ug+rw $trac_prj_envdir $trac_prj_bzrdir		|| exit $?
echo "ok"


# create apache2 snipped file
#
outfile="/etc/apache2/conf.d/ku-trac-$prjname.conf"
tmpfile="/tmp/trac-$prjname.conf"
template=`ku_get_template trac-apache2-conf`			|| exit $?

echo -n "  creating apache2 config file $outfile ... "
kusa-conf-parse --include $tmpconf $template >$tmpfile		|| exit $?
mv $tmpfile $outfile						|| exit $?
echo "ok"

invoke-rc.d apache2 reload

rm -f $tmpconf

exit 0
