#!/usr/local/bin/python
# -*- coding: iso-8859-1 -*-
#
# wikiput.py v1.0
#
# Update a Moin page.
#
# By: Max Campos <mcampos@bpsw.biz>
# Sept. 1, 2005

import sys
import os

def parseOpts():
	from optparse import OptionParser

	usage = "usage: %prog [options] SomePage < page.txt"
	op = OptionParser(usage=usage)
	op.add_option('-w', '--wikidir', dest='wikidir', 
		help="Dir containing your wikiconf.py");
	
	op.add_option('-u', '--user', dest='user',
		help="Username to make changes as")

	op.add_option('-c', '--comment', dest='comment', default='',
		help="Comment")
	
	op.add_option('-t', '--trivial', dest='trivial', action='store_true', 
		help="Trivial change?")

	op.add_option('-x', '--ignore-unchanged', dest='ignore_unchanged',
		action='store_true', help='Silently ignore edits which do not change the page?')

	op.add_option('-p', '--print', dest='prt', action='store_true', 
		help='Print the new raw page text')
		
	(options, args) = op.parse_args()
	if len(args) > 0:
		options.pagename = args[0]
	else:
		op.error("You must specify a page name.")

	return options
	
	
opts = parseOpts() or sys.exit(1)

# Do chdir to the wikidir so that any relative file paths in
# the wiki config work.
if opts.wikidir:
	os.chdir(opts.wikidir)
	sys.path.append(opts.wikidir)

from MoinMoin.request import RequestCLI
from MoinMoin.PageEditor import PageEditor
from MoinMoin.user import User
from datetime import datetime
from MoinMoin.Page import Page
request = RequestCLI(url='foo')
request.user = User(request=request, auth_username=opts.user)
request.form = {}
ed = PageEditor(request, opts.pagename, trivial=opts.trivial)

newtext = sys.stdin.read()

try:
	ed.saveText(newtext, 0, comment=unicode(opts.comment) or u'')
except PageEditor.Unchanged:
	if not opts.ignore_unchanged:
		raise

# Return the raw wiki text.
if opts.prt:
	p = Page(request, opts.pagename)
	print p.getPageText()

