#!/usr/bin/perl -w

#This script is written to add virtual hosts to a very simple
#installation of Tomcat in order to achieve a simple and
#(crucially) comprehensible method of just making the 
#damn thing work [TM]
#
# (C) 2005 Peter Stevens
#
# http://www.ex-parrot.com/~pete/
#
# Virtual Linux Servers, ideal for running Tomcat
# http://www.mythic-beasts.com/vds.html
#
#
#
# Written in Perl because java is useless at integrating with 
# system utilities.

$tomcatdir = "/usr/local/tomcat";

($host, @aliases) = @ARGV;

print "Adding virtual host $host\n";
foreach $alias (@aliases) {
	print "Adding alias $alias for $host\n";
}

print "Stopping Tomcat\n";
`$tomcatdir/bin/shutdown.sh`;


print "Editing $tomcatdir/conf/server.xml\n";

open (FILE, "$tomcatdir/conf/server.xml") || die "Can't open server.xml";
open (NEWFILE, ">$tomcatdir/conf/new-server.xml") || die "Can't open new-server.xml";

while ($buf = <FILE>) {

	if ($buf =~ /VIRTUAL HOST INJECTION POINT/) {
		print "Injecting $host\n";

print NEWFILE <<endvhost;

<Host name="$host" debug="0" appBase="webapps/$host"
	unpackWARs="true" autoDeploy="true"
    xmlValidation="false" xmlNamespaceAware="false">

<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs"  prefix="$host\_log." suffix=".txt" timestamp="true"/>

endvhost
;

foreach $alias (@aliases) {
print NEWFILE "<Alias>$alias</Alias>\n";
}

print NEWFILE "</Host>\n\n";

	}
	print NEWFILE $buf;
}

close NEWFILE;
close FILE;

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = gmtime(time);
$now = ($year + 1900) . ($mon + 1) . 
`cp $tomcatdir/conf/server.xml $tomcatdir/conf/server-\`date -Iseconds\`.xml`;
`mv $tomcatdir/conf/new-server.xml $tomcatdir/conf/server.xml`;

print "Making blank directory\n";

`mkdir $tomcatdir/webapps/$host`;
`mkdir $tomcatdir/webapps/$host/WEB-INF`;
`mkdir $tomcatdir/webapps/$host/WEB-INF/classes`;
`mkdir $tomcatdir/webapps/$host/WEB-INF/lib`;

open (FILE, ">$tomcatdir/webapps/$host/WEB-INF/web.xml") || die "Can't open web.xml";

print FILE <<webapp;
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
</web-app>

webapp
;

close FILE;

print "Making holding page\n";
open (FILE, ">$tomcatdir/webapps/$host/index.jsp") || die "Can't open index.jsp";

print FILE <<index;
<html>
<head>
<title>Not yet configured</title>
</head>

<body>
<p>This virtual server $host is not yet configured.</p>
</body>
</html>
index
;

close FILE;


print "Writing config\n";
`mkdir $tomcatdir/conf/Catalina/$host`;

open (FILE, ">$tomcatdir/conf/Catalina/$host/ROOT.xml") || die "Can't open ROOT.xml";
print FILE <<ROOT;
<?xml version='1.0' encoding='utf-8'?>
<Context displayName="$host" docBase="" path="" workDir="work/Catalina/$host/_">
</Context>

ROOT
;
close FILE;

sleep(5);



print "Starting Tomcat\n";
`$tomcatdir/bin/startup.sh`;
