#!/usr/bin/perl -w

# handle_put.cgi
# Basic PUT Handling routine with NO SECURITY !

my $maxLength = 100000;

if($ENV{'REQUEST_METHOD'} ne 'PUT') {
   errorMsg("Request method is not PUT");
}

my $filename = $ENV{'PATH_TRANSLATED'};
if(not $filename) {
   errorMsg("PATH_TRANSLATED was empty");
}

my $length = $ENV{'CONTENT_LENGTH'};
if(not $length) {
   errorMsg("CONTENT_LENGTH was empty");
}

# Add Security Checks Here!
# - Restrict to certain directories
# - Limit size and/or type of file
# - For example:
if($length > $maxLength) {
   errorMsg("CONTENT_LENGTH is too large"); 
}

# Read in the uploaded data in on gulp
my $content = '';
my $nread = read(STDIN, $content, $length);

# Make the output more readable by addng newlines
$content =~ s/\>\</\>\n\</g;

# Write the file on the web server
open OUT, "> $filename" || errorMsg("Unable to open $filename");
print OUT $content;
close OUT;

# The 204 code signals the transfer was OK but does not 
# update the current page - so you stay in the editor
print qq[Status: 204\n];
print qq[Content-type: text/html\n\n];
print $content;
exit;

#----------------------------------------------------

sub errorMsg {
   my $msg = shift;
   print qq[Content-type: text/html\n\n];
   print qq[<html><head><title>Error</title></head>\n];
   print qq[<body>\nError: $msg<br>\n</body></html>\n];
   exit;
}