#!/usr/bin/perl -w

# Copyright (C) 2003 Vincent Caron <v.caron@zerodeux.net>
# This script is part of Savannah <savannah.gnu.org>

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


#  sv_sync_www.pl - Ask a web host to sync its working copy from CVS
#
#  Usage :
#
#  Add this line in the CVSROOT/loginfo file of the repository you want to watch :
#
#  ALL     ( /subversions/sourceforge/bin/sv_sync_www.pl %s & ) >> /var/log/sv_sync_www.log

use strict;
use POSIX qw(strftime);
use LWP;

my $sync_url;


# Send sync event to CGI at $sync_url.
#
# Input: the '%s' argument as substitued by CVSROOT/loginfo.
# Output: command status (0 is success).
#
sub do_event {
    my $event = shift;
    my $path = '';
    my @files = split / /, $event;

    if ($event =~ / - New directory$/ or
        $event =~ / - Imported sources$/) {
        $path = $files[0];
        @files = ();
    } else {
        $path = shift @files;
    }

    # Build request
    my $req = HTTP::Request->new(POST => $sync_url);
    $req->content_type('application/x-savannah-sync');
    $req->content("$path\n");
 
    # Build a user agent
    my $ua = LWP::UserAgent->new;
    $ua->agent('sv_sync_www.pl');

    # Issue request
    my $res = $ua->request($req);

    # Log event with return code
    my $date = strftime "%Y-%m-%d %H:%M:%S", localtime(time());
    print "$date - $event - ". $res->code ." ". $res->message ."\n";

    return $res->is_success;
}

sub usage {
    print STDERR "Usage: sv_sync_www.pl http://host/cgi-bin/sync[:port] files...\n";
    exit 1;
}

usage() if (@ARGV < 2);

$sync_url = shift @ARGV;
usage() if (not $sync_url =~ /http:\/\//);

exit(do_event (shift @ARGV));
