#!/usr/bin/perl --
# -*- Mode: perl; indent-tabs-mode: nil -*-
#

# This script does not need to run under taint perl.

# HTTPost.cgi - A perl script for uploading datafiles to the
# Webserver. Via HTTP Post.

# Taken from code found on the mailing list:
#    http://www.mail-archive.com/modperl@apache.org/msg35695.html
#    * From: Steve Bannerman
#    * Subject: HTTP POST: parameters "empty" when using ModPerl::Registry (okay when using ModPerl:PerlRun)...
#    * Date: Thu, 14 Aug 2003 11:38:50 -0700

# $Revision: 1.2 $ 
# $Date: 2004/07/10 14:47:34 $ 
# $Author: kestes%walrus.com $ 
# $Source: /cvsroot/mozilla/webtools/tinderbox2/src/clientbin/HTTPPost,v $ 
# $Name:  $ 


# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/NPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Tinderbox build tool.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#

# complete rewrite by Ken Estes for contact info see the
#     mozilla/webtools/tinderbox2/Contact file.
# Contributor(s): 

# Standard perl libraries

use LWP::UserAgent;
use HTTP::Request::Common;

# Tinderbox libraries

use lib '/usr/share/tinderbox/lib', '/etc/tinderbox';

use TinderConfig;
use Utils;

$VERSION = '0.09';


sub usage {

    my $usage =<<EOF;

$0	http://servername/for/build/processing

Synopsis

This program performs a HTTP Post operation of the contents of STDIN
to the URL supplied by the first argument.

This program can be used to send tinderbox logs to the tinderbox
server, replacing sendmail. For this to work the processmail script must 
be located in a cgi directory.

Errors are logged to the logfile: $ERROR_LOG


EOF

    print $usage;
    exit 0;

} # usage



sub post {
    my ($postUrl) = @_;

    # read all of STDIN into a string
    undef $/;
    my $data = <STDIN>;
    
    my $postType = 'form-data';
    
    my $ua = new LWP::UserAgent;
    my $req = POST($postUrl,
		   Content_Type => $postType,
		   Content => $data);
    
    my $res = $ua->request($req);
    
    if (!($res->is_success())) {
	print STDERR "HTTP POST failed";
	print STDERR "code: " . $res->code() . "\n";
	print STDERR "message: " . $res->message() . "\n";
	die("\n");
    }

    return ;
}



# --------------------main-------------------------
{
  set_static_vars();
  get_env();

  if (
      (!($ARGV[0])) ||
      ($ARGV[0] =~ m/-?\?/) ||
      ($ARGV[0] =~ m/help/) 
      ) {
      usage();
  }

  my $postUrl = $ARGV[0];

  post($postUrl);
  
  exit 0;
}
