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

Usage::
    
    python append-text url pagename file

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.

file is just an example, you might want to customize this script to
read the data from another process, the web or whatever.

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 = [# 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'] + sys.path


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


def append(url, pagename, text):
    request = RequestCLI(url=url, pagename=pagename)
    editor = PageEditor(request, pagename)
    text = editor.get_raw_body() + editor.normalizeText(text)
    dummy, revision, exists = editor.get_rev()
    return editor.saveText(text, revision)


if __name__ == '__main__':
    """ Example: reading from file on disk using config.charset """
    import codecs
    from MoinMoin import config
    try:
        url, pagename, filename = sys.argv[1:]
        text = codecs.open(filename, 'r', config.charset).read()        
        append(url, pagename, text)
    except ValueError:
        print __doc__
