#!/usr/bin/perl -w
#
# This is a basic interface to append an Oddmuse wiki page. I used
# that in order to keep a list of things to do or remember (like url). 
# Very nifty if you have only an SMTP client available. 
# The data appended is from the "Subject" header only.
# 
# The installation can be done via procmail or a mail alias entry like :
# 
# anemailalias: "|perl /usr/bin/oddmail.pl"
#
# Copyright (C) 2004  Alex Schroeder <alex@emacswiki.org>
# Copyright (C) 2006  Alexandre (adulau) Dulaunoy
#
# 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 strict;
use Getopt::Std;
use LWP::UserAgent;

my $VERSION = "0.0.1";
$| = 1;

my $target = "http://www.foo.be/cgi-bin/wiki.pl";
my $page   = "GTD";
my $user   = "adulau";
my $pwd    = "something";
my $entry;

sub UrlEncode {
  my $str = shift;
  return '' unless $str;
  my @letters = split(//, $str);
  my @safe = ('a' .. 'z', 'A' .. 'Z', '0' .. '9', '-', '_', '.', '!',
	      '~', '*', "'", '(', ')', '#');
  foreach my $letter (@letters) {
    my $pattern = quotemeta($letter);
    if (not grep(/$pattern/, @safe)) {
      $letter = sprintf("%%%02x", ord($letter));
    }
  }
  return join('', @letters);
}

sub GetRaw {
  my ($uri) = @_;
  my $ua = LWP::UserAgent->new;
  my $response = $ua->get($uri);
  return $response->content if $response->is_success;
}


sub PostRaw {
  my ($uri, $id, $data, $user, $pwd) = @_;
  my $ua = LWP::UserAgent->new;
  my $response = $ua->post($uri, {title=>$id, text=>$data, raw=>1,
				  username=>$user, pwd=>$pwd});
  warn "POST $id failed.\n" unless $response->is_success;
}

sub append {
  my ($target, $page, $user, $pwd) = @_;
  $page =~ s/ /_/g;
  $page = UrlEncode ($page);
  my $data = GetRaw("$target?action=browse;id=$page;raw=1");
  my $lDate = localtime;

  $data .= "* ".$entry." (".$lDate.")\n";
  PostRaw($target, $page, $data, $user, $pwd);
}


while (<STDIN>) {

	if (/^Subject/) {
		s/Subject:\ //i;
		$entry = $_;
	}

}

append($target, $page, $user, $pwd);

