#!/usr/bin/env python
"""
Append text to a wiki page
==========================

Usage::
    
    python append-text url pagename filename

Append the text in filename to the page url/pagename, saving a backup
of the old revision and updating the logs. This should be equivalent to
editing the page manually with a browser.

filename can be any file or file like object using any charset.

If pagename does not exists, it is created automatically. If pagename
is an underlay page, it will be copied into the data directory before
the edit is performed.

You should run the script with the same user and group as used by the
the wiki server, e.g. 'www-data', or the new revisions might be saved
with wrong owner, which will cause an IOError later when browsing the
wiki.

Examples::

    sudo -u www-data python append-text.py 'localhost/mywiki/' \
        'Additions'  'additions.txt'

Require MoinMoin release 1.3, tested with 1.3.4 patch 718. 

WARNING: EXPERIMENTAL, USED WITH CATION!


@copyright: 2005 by Nir Soffer <nirs@freeshell.org>
@license: GNU GPL, see COPYING for details.
"""

# Path configuration
import sys
sys.path = sys.path + [
    # The path to the wiki directory
    '/Volumes/Home/nir/wiki/fix',
    # The path to moinmoin, not needed if its installed with setup.py
    '/Volumes/Home/nir/Projects/moin/fix']


import codecs

from MoinMoin import config
from MoinMoin.PageEditor import PageEditor
from MoinMoin.request import RequestCLI


def append(url, pagename, filename):
    """ Append text in filename to url/pagename """
    request = RequestCLI(url=url, pagename=pagename)
    page = PageEditor(request, pagename)
    text = codecs.open(filename, 'r', config.charset).read()
    text = page.get_raw_body() + text
    text = page.normalizeText(text)
    dummy, revision, exists = page.get_rev()
    return page.saveText(text, revision)


if __name__ == '__main__':
    try:
        url, pagename, filename = sys.argv[1:]
        print append(url, pagename, filename)
    except ValueError:
        print __doc__