#!/usr/bin/perl -w
# This program keeps version-controlled web pages with CVS up to date.
# Each commit is immediately checked out again in your website.
#
# Usage: (assume abc is your website useraccount)
# 1 add to CVSROOT/loginfo: DEFAULT echo %s | /usr/bin/mail -s "cvs" abc
# 2 add to ~abc/.forward: "|/fullpathto/checkthisout.pl"
# 3 edit $webroot and $CVS_root_directory below
# You can test the script without committing too by faking the cvs mails:
# echo "firstdirundercvsroot/dir file1 file2 file3" | mail -s "cvs" abc
#
# $Id: checkthisout.pl,v 1.5 2004/08/17 19:47:40 hans Exp $
# License: http://www.opensource.org/licenses/artistic-license.html
# Improvements are welcome, email them to hans@lambermont.dyndns.org.NOSPAM
use strict;

# point this to where your website checks out
my $webroot = "/usr/local/share/apache";

# point this to the root directory of the master source repository.
# aka $CVSROOT
my $CVS_root_directory = "/var/cvs/intranetroot";

my $cvs = "cvs -Q -R -d $CVS_root_directory update -d";
#$cvs = "echo "; # enable this line for testing

chdir $webroot || die "Couldn't chdir to $webroot";

open (LOG, ">> $webroot/maillog") || die "could not open maillog";
print LOG "------------------------\n";

# skip_mail_header
while (<STDIN>) {
	chomp;
	print LOG "H [" . $_ . "]\n";
	last if $_ eq '';
}

while (<STDIN>) {
	chomp;
	print LOG "B [" . $_ . "]\n";
	my ($cvsdir, @files) = split / /, $_;
	$_ = "@files";
	my ($repository) = $cvsdir;
	$repository =~ s/^([^\/]*)\/.*$/$1/;
	print LOG "cvsdir=[$cvsdir], repository=[$repository], files=[$_]\n";
	if ("@files" eq "- New directory") {
		print LOG "New directory: $webroot/$cvsdir\n";
		# be blunt for now ...
		chdir "$webroot/$repository" ||
			print LOG "ERROR Could not chdir to $webroot/$repository\n";
		my $err = system("$cvs");
		print LOG "Command [$cvs] returned error code [$err]\n";
		if ($err) {
			print LOG "ERROR cvs returned error $err\n";
			die "cvs returned error $err\n";
		}
	} elsif (@files) {
		print LOG "cd $webroot/$cvsdir\n";
		chdir "$webroot/$cvsdir" ||
			print LOG "ERROR Could not chdir to $webroot/$cvsdir\n";

		my $err = system("$cvs @files");
		print LOG "Command [$cvs @files] returned error code [$err]\n";
		if ($err) {
			print LOG "ERROR cvs returned error $err\n";
			die "cvs returned error $err\n";
		}
	}
}

close(LOG);
