#!/usr/local/bin/perl

if ($#ARGV != 2) {
        print "Usage: $0 <target host> <input file> <output file>\n";
        print "input file should contain directory structure relative to web root /\n\n";
        exit(1);
}

my $host = $ARGV[0];
my $infile = $ARGV[1];
my $outfile = $ARGV[2];

$port = 80;
$blah = "HTTP/1.0\nHost: $host\nContent-length: 4\nTEST\n";

open(OUT, ">$outfile") or die("unable to open $outfile: $!");
open(IN, $infile) or die("unable to open $infile: $!");
@directories=<IN>;

foreach (@directories) {
	chomp;
	print OUT "$_ --> ";
	s/ /%20/g;
	my $repl = echoToNc(qq(PUT /$_/test.txt $blah));

	if ($repl =~ /not allowed/i) { print OUT "Not Allowed\n"; }
	elsif ($repl =~ /403.4 Forbidden: SSL required/i) { print OUT "* 403.4 Forbidden: SSL required *\n"; }
	elsif ($repl =~ /401 Unauthorized/i) { print OUT "401 Unauthorized\n"; }
	elsif ($repl =~ /Error 404/i) { print OUT "Error 404\n"; }
	elsif ($repl =~ /Write Access Forbidden/i) { print OUT "Write Access Forbidden\n"; }
	elsif ($repl =~ /Unauthorized due to ACL on resource/i) { print OUT "Unauthorized due to ACL on resource\n"; }
	#else { print OUT "*** SUCCESSFULL PUT ***\n"; exit(0); }
	else { print OUT "*** SUCCESSFULL PUT ***\n"; }
}

sub echoToNc {
	my($cmd) = @_;
	open (CMD, ">/tmp/puttestin.$$.txt") or die "Can't open /tmp/puttestin.$$.txt: $!";
	print CMD "$cmd\n";
	print "== Sending the following:\n$cmd";
	print `nc $host $port < /tmp/puttestin.$$.txt > /tmp/puttestout.$$.txt`;
	print "== Got the response:\n";
	open (TMPOUT, "/tmp/puttestout.$$.txt") or die "Can't open /tmp/puttestout.$$.txt: $!";
	my(@lines) = (<TMPOUT>);
	my($lines) = join("",@lines);
	print $lines;
	return $lines;
}
