#!/usr/bin/perl -w

use strict;
use WWW::Mediawiki::Client;
use Getopt::Std;
use Pod::Usage;

##############################################################################
# Constants                                                                  #
##############################################################################
use constant WIKITRAVEL_DEFAULTS =>
          'edit_path' => 'wiki/en/index.php?action=edit&title=',
          'login_path' => 'wiki/en/index.php?action=submit&title=Special:Userlogin',
          'action_path' => 'wiki/en/index.php?action=submit&title=',
          'space_substitute' => '_',
    ;

use constant WIKIPEDIA_DEFAULTS =>
          'space_substitute' => '+',
          'action_path' => 'w/wiki.phtml?action=submit&title=',
          'edit_path' => 'w/wiki.phtml?action=edit&title=',
          'login_path' => 'w/wiki.phtml?action=submit&title=Special:Userlogin',
    ;

##############################################################################
# Fields                                                                     #
##############################################################################
our ( $opt_h, $opt_q, $opt_d, $opt_v, 
      $opt_m, $opt_u, $opt_p, $opt_s,
      $opt_e, $opt_a, $opt_l);    # Getopt output
our $VERSION = $WWW::Mediawiki::Client::VERSION;

$Getopt::Std::STANDARD_HELP_VERSION = 1;

##############################################################################
# Subroutines                                                                #
##############################################################################

sub main {
    my $command = shift;
    pod2usage unless $command;
    my $method= "do_$command";
    # do help if indicated
    pod2usage(-verbose => 1) if $opt_h;
    # create the init array, and maybe pre-populate it
    my @init;
    @init = WIKIPEDIA_DEFAULTS
            if $opt_d and $opt_d =~ /^http:\/\/[^\.]*\.wikipedia\.org/;
    # FIXME: this is a hack which deals with the language versions of
    # Wikitravel.  What I really should do is to replace the various x_path
    # fields in the $wmc object with the proper name value pairs from
    # Mediawiki.
    if ($opt_d and $opt_d =~ m{^http://www\.wikitravel\.org(/en|/fr|/ro|/sv|/de)*}) {
        @init = WIKITRAVEL_DEFAULTS;
        my $lang = $1;
        if ($lang) {
            my %init = @init;
            for (values %init) { s{/en/}{$lang/} };
            @init = %init;
            $opt_d = 'http://www.wikitravel.org';
        }
    }
    # instanciate a WWW::Mediawiki::Client obj
    my $wmc = WWW::Mediawiki::Client->new(@init);
    unless ($wmc->can($method)) {
        print "Command \"$command\" not supported.\n\n";
        pod2usage(-verbose => 1);
    }
    $wmc->site_url($opt_d) if $opt_d;
    $wmc->output_level(WWW::Mediawiki::Client::DEBUG) if $opt_v;
    $wmc->output_level(WWW::Mediawiki::Client::QUIET) if $opt_q;
    $wmc->commit_message($opt_m) if $opt_m;
    $wmc->username($opt_u) if $opt_u;
    $wmc->password($opt_p) if $opt_p;
    $wmc->space_substitute($opt_s) if $opt_s;
    $wmc->action_path($opt_a) if $opt_a;
    $wmc->edit_path($opt_e) if $opt_e;
    $wmc->login_path($opt_l) if $opt_l;
    # run command
    $wmc->$method(@_);
}

sub HELP_MESSAGE {
    pod2usage(-verbose => 1);
}

sub VERSION_MESSAGE {
    my $fh = shift;
    print $fh "wix Mediawiki versioning system version $VERSION\n";
}


# parse command line
getopts('hqvd:m:u:p:s:e:a:l:');
main (@ARGV);

__END__

=head1 NAME

wix - A command line wiki client 

=head1 SYNOPSIS

  wix [Options] command [Options] [filename]

  wix -h|--help
  wix --version

  mkdir wikistuff
  cd wikistuff

  wix [-q|-v] [-d <wikihost>] [-u <username>] [-p <password> ] login

  wix [-q|-v] update [<file> ..]
  wix [-q|-v] up [<file> ..]

  wix [-q|-v] commit [<file> ..]
  wix [-q|-v] com [<file> ..]

=head1 DESCRIPTION

C<wix> is a command line client whose purpose is to simplify offline
editing of Wiki content.  It allows you to get any number of pages from a
given Mediawiki site, edit the pages with any editor, get and merge any
concurrent updates of the pages, and then safely commit the users own
changes back to the version of the page on the server.

The C<wix> commands which take a filename argument only accept a single
filename as so to avoid taking up too much server bandwidth.

=head1 QUICKSTART

=head2 Step 1:  Create an account on the Mediawiki server.

This should be done the normal way, by visiting the mediawiki website to
which you want to contribute and creating a new account, setting the
preferences, etc.

It should hopefully go without saying that you will want to become familiar
with the editorial, usage, and copyright guidelines of the site.  You
should probably also make some contributions through the normal UI, and
learn about following recent changes before contributing using wix.

In addition for the sake of this test you should already have a user page
like User:<username> with something on it, where <username> is the user
name with which you estabilished the account.

=head2 Step 2:  Create a working directory

Wix works with mediawiki formatted files with a C<.wiki> extension and
which are stored together with server information in a I<working directory>.  
You will have to have I<at least> one working directory for each Mediawiki
site to which you contribute.

Simply use C<mkdir> or the equivalent to make a new directory, and then
before cd into that directory.

  mkdir wikitravel.en
  cd wikitravel.en

All of the operations below should be done from this directory.

=head2 Step 3:  Login using C<wix login>

To use login you will need to know the I<site_url> for the Mediawiki site
to which you want to contribute.  This will simply be the regular URL for
the site, with any language path extension.  For instance for the english
version of Wikitravel I would use the I<site_url>

  http://www.wikitravel.org/en

Now use the I<site_url> with your username and password to login.

  wix -d http://www.wikitravel.org/en -u <username> -p 'secret' login

Now anything you submit to the Mediawiki server will be credited to user
"<username>".

=head2 Step 4:  Use C<wix update> to fetch one or more working files

You can fetch existing material off of the site, or create new pages with
C<wix update>, remembering that your files will need a C<.wiki> extension:

  wix update User:<username>.wiki User:<username>/Test_Page.wiki

This should produce the output:

  U User:<username>.wiki
  A User:<username>/Test_Page.wiki

The U (for Updated) means that User:<username> was found on the server and
its contents inserted into the local files.  The A (for Added) means that
the User:<username>/Test_Page.wiki page does not yet exist on the server,
and will be added when you run C<wix commit>.

Note that both of the pages we are working with are within I<your>
User Namespace.  It's probably a good idea to restrict yourself to working
with such pages while you are experimenting with C<wix>

=head2 Step 5:  Edit the files to make corrections and contributions

Use your favorite text editor to edit the files.  You might want to check
out this page to see if there is a Mediawiki syntax highlighting file for
your editor:

  http://en.wikipedia.org/wiki/Wikipedia:Syntax_highlighting

Of course if you don't find a highlighting file for you editor you are
welcome to create one and submit it to the page above.

=head2 Step 6:  Use C<wix commit> to submit your changes

When you are done editing a file and would like to submit your changes to
the wiki server use C<wix commit> to do so:

  wix -m 'commit message' commit User:<username>.wiki

Where 'commit message' is whatever you want to say about the changes you
are submitting and why.  You must provide a commit message or C<wix commit>
will fail.  You might also find that C<wix commit> fails complaining that
the file has changed on the server.  If this is the case you will need to
use C<wix update> again to get the most recent changes.

=head2 Step 7: Update your wiki files

You can use C<wix update> again at any time to reconcile any of your files
with the most recent changes from the server.  Your changes I<will not> be
overwritten, but rather C<wix> will try to merge any server changes into
the files as they exist in your working directory.  Note that update and
commit only work on one file at a time, as so to help prevent accidents and
server congestion.

If for some reason there is a conflict, ie. you and someone else have made
changes which appear to be incompatible, and cannot be resolved then your
file will contain a I<conflict message>, as detailed in the documentation
for C<wix update> below.  You I<must> resolve any conficts I<before>
attempting to use C<wix commit> on the file.  This is usually a very simple
matter of choosing one version of the change or another.  You should use
your best judgement, consulting the relavant C<Talk:> page to try to work
out an aggreement with the other contributor in cases where you just simply
disagree.

=head2 Repeat

You can continue editing and commiting changes with the files in your
working directory.  It might be a good idea for you to eventually create
multiple working directories per site, perhaps grouping them by subject.
This will work fine with C<wix> since it does I<not> need to have a
complete copy of all of the pages from a given server in a given working
directory to work.

=head1 ARGUMENTS

=head2 Commands

The first argument after the options should be one of the following two
commands:

=over 4

=item wix login

Allows the user to login to the Mediawiki server using an I<existing> login
and password for that server.  After calling C<login> ll C<commit>s from
the same working directory will be logged as from the logged-in user.

=item wix update

Updates the specified file[s] with content from the Mediawiki server.  If a
file does not exist it is created and populated with the current online
version.  If there is no online version, the file either created and left
blank, or just left as it is.  If there is content in both the specified
file and in the cooresponding Wiki page, an attempt is made to merge the
two, line by line.  Files which are the same as the server version are
ignored.

If no filenames are given on the command line, all visible files with the
.wiki extension are processed.

Conflicting changes to a given line are detected on the basis of the date
of the most recent update of the local file and date of the most recent
change to the online Wiki page.  If a line has changed in both the online
page and the local file it is flagged as a conflict, as in CVS, but with a
slightly differnt syntax:

  >>>>>> http://www.somewiki.org
  This is the version on the Wiki
  >>>>>> Paris.wiki
  This is the local version
  <<<<<<

C<wix update> reports the status of files which it touches to stderr with
a letter indicating the file status, and then name of the file, again like
CVS.  The status letters are:

=over 4

=item A (Added) 

The file will become a new page on the wiki server.

=item M (Modified) 

The file has been modified locally.

=item U (Updated) 

The file has been updated with changes from the wiki server.

=item C (Conflicts) 

The file contains conflict markers.

=back

=item commit

Commits any changes in the specified local files to the Wiki site.  A check
is made first to make sure that there are no changes on the server more
recent than the most recent update.  Files which are the same as the server
version are ignored.

If no filenames are given on the command line, all visible files with the
.wiki extension are processed.

When running C<wix commit> you I<must> use the C<-m> flag to send a commit
message to the Mediawiki server.  eg:

  wix -m 'Added Hotel Eldorado' commit Paris.wiki

=back

=head2 File names

Any additional arguments are taken as I<local> filenames to be processed.
The local filename of a given Mediawiki page will be the same as its URL
encoded name with the extension ".wiki".  If no arguments are given then
any filenames with the "wiki" extension and under the current directory are
processed.

=head1 OPTIONS

=head2 -h

Display usage information.

=head2 -q

Causes the command to be quiet.  Informational messages are suppressed.

=head2 -u

Specifies a username for C<wix login>.

=head2 -p

Specifies a password for C<wix login>.

=head2 -m

A commit message for C<wix commit>.  Use this to explain the nature of your
changes.

=head2 -e

The mediawiki edit path.  For use with Mediawiki servers which have an
altered path to a page's edit page.

=head2 -a

The mediawiki action path.  For use with Mediawiki servers which have an
altered path to a page's action page.

=head2 -l

The mediawiki login path.  For use with Mediawiki servers which have an
altered path to a page's login page.

=head1 CAVEATS

This is an early version of this program.  Future versions may have major
differences which will effect your ability to use them interchangably with
this one.  In particular the initial "command" arguments may become
options and the handling of conflicts might change dramatically.

=head1 SEE ALSO

=head2 Mediawiki

L<http://www.wikimedia.org|Mediawiki>

=head2 CVS

L<http://www.cvs.org|The CVS home page>

=head1 AUTHORS

Mark Jaroski <mark@geekhive.net>

=head1 COPYRIGHT

 Copyright 2004, Mark Jaroski

All rights reserved. This program is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.

