#!/usr/bin/perl 
#   pmwe  (pmwikiedit)
#   Copyright 2002 Jonathan Scott Duff 
#   duff@pobox.com
#
#   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

use LWP::Simple;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);
use Getopt::Std;

$DefaultWikiUrl = 'http://www.pmichaud.com/wiki/';
$DefaultWikiPage = 'Main/WikiSandbox';
$DefaultWikiEditor = 'vi';

package PmWikiAgent;

@ISA = qw(LWP::UserAgent);
 
sub new {
   my $self = LWP::UserAgent::new(@_);
   $self->agent("pmwikiedit");
   return $self;
}
 
sub get_basic_credentials
{
   my($self, $realm, $uri) = @_;
   print "Enter password for $realm: ";
   system("stty -echo"); chomp(my $password = <STDIN>); system("stty echo");
   print "\n";  # because we disabled echo
   return ("pmwikieditor", $password);
}

package main;

my %opts;
getopts('m:', \%opts);

$mapfile = $opts{'m'} || "$ENV{'HOME'}/.pmwe.map";
if (open(MAP, $mapfile)) {
   while (<MAP>) { my ($n,$url) = split; $urlmap{$n} = $url; }
   close MAP;
}

$editor = $ENV{'EDITOR'} || $DefaultWikiEditor;

($wikipage,$wikiurl) = @ARGV;
$wikiurl = $urlmap{$1} if $wikipage=~s/^(\w+):// && !$wikiurl && $urlmap{$1};

$wikipage ||= $DefaultWikiPage; $wikipage =~ tr!/!.!;
$wikipage .= ".$wikipage" unless $wikipage =~ /\./;
$outfile = "/var/tmp/$wikipage.$$";

$wikiurl ||= $DefaultWikiUrl;
$wikiurl .= "/" unless $wikiurl=~m!/$!;
$content = getstore("$wikiurl$wikipage?action=source",$outfile);

$mtime0 = (stat($outfile))[9];
system("$editor $outfile");
$mtime1 = (stat($outfile))[9];
if ($mtime0 == $mtime1) 
   { print STDERR "content unchanged.\n"; unlink($outfile); exit; }

open(OUTFILE, "$outfile") or die;
{ local $/; $text = <OUTFILE>; }
close OUTFILE;

$text =~ s/\s*$//s;
my $ua = PmWikiAgent->new;
my $req = POST $wikiurl, [
   action	=> 'post',
   pagename	=> $wikipage,
   text		=> $text,
];
$ua->request($req);
unlink($outfile);

