#!/usr/bin/perl -wT
#this is not ment to ever be called interactively.
#just as a netscape mime handler for application/vesta-action

use strict;

sub untaint($);

$ENV{PATH} = "/bin:/usr/bin:/sbin:/usr/sbin";
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};

my $vestabin = "/vesta-srv/bin";

open(CF, "<$ARGV[0]") or die "couldn't open command file $ARGV[0]: $!";
my %command = ();
while (my $command = <CF>) {
	last if($command eq "\n" && $command{action} eq "checkin");
	my ($name, $value) = split /: /o, $command;
	$command{$name} = untaint $value;
}
my $message;
if($command{action} eq "checkin") {
	$message = join("", <CF>);
	#just make -T happy...  we don't actually care what they put in here.
	chomp $message;
	$message =~ s/(.*)/$1/o;
}
close CF;
unlink untaint $ARGV[0];

my $euid = (getpwuid($>))[0];
die "My uid doesn't match who I was told I am! euid:$euid user:$command{user}." if $euid ne $command{user};

my @commandline;
my $workingdir;
if( defined($command{work_dir}) && -d $command{work_dir} ) {
	$workingdir = $command{work_dir};
} elsif($workingdir = `$vestabin/vattrib -G -q default-working-dir-name $command{package}`) {
	chomp $workingdir;
} else {
	#default magic value
	$workingdir = join("-", (split(/\//o, $command{package}))[-2, -1]);
}
if($command{action} eq "exclusive") {
	@commandline = ("$vestabin/vcheckout","-q","-w",$workingdir,$command{package});
} elsif($command{action} eq "scribble") {
	@commandline = ("$vestabin/vcheckout","-q","-w",$workingdir,"-N",$command{package});
} elsif($command{action} eq "checkin") {
	@commandline = ("$vestabin/vadvance","-q",$workingdir);
	system(@commandline);
	@commandline = ("$vestabin/vcheckin","-m",$message,"-q",$workingdir);
} else {
	die "I don't know how to $command{action}!";
}

system(@commandline);
system(("$vestabin/vattrib","-a","user-agent","vestaweb","$command{package}/$command{version}"));
exit 0;

sub untaint($) {
	my $str = shift;
	if($str =~ /^([-\/\.\w]+)$/o) {
		return $1;
	} else {
		return undef;
	}
}
