#!/usr/bin/python

from optparse import OptionParser
import urllib, httplib
from urlparse import urlparse
import os
import time
from wicilib.util import *

def main():
	""" main function """

	# guess the editor
	if os.environ.has_key('EDITOR'):
		EDITOR = os.environ['EDITOR']
	elif os.path.exists('/usr/bin/editor'):
		EDITOR = '/usr/bin/editor'
	else:
		EDITOR = 'cat'

	parser = OptionParser('%prog [options] <pagename>', version = '%prog 0.1')
	parser.add_option("-d", "--directory", action="store", dest="directory", default=None, help="use DIRECTORY as the wikitext pathname of the WikiWiki")
	parser.add_option("-u", "--username", action="store", dest="username", default=None, help="specify a username")
	parser.add_option("-p", "--password", action="store", dest="password", default=None, help="specify a password")
	parser.add_option("-e", "--editor", action="store", dest="editor", default=EDITOR, help="use EDITOR as the editor for WikiWiki")
	parser.add_option("-w", "--wiki", action="store", dest="wiki", default='moniwiki', help="specify WikiWiki engine")

	options, args = parser.parse_args()

	wiki_text_path = options.directory or guess_wiki_path()

	if args:
		title = args[0]
	else:
		title = 'FrontPage'

	if not urlparse(wiki_text_path).scheme:
		# wiki_text_path is not an url
		file_name = os.path.join(wiki_text_path, wiki_encode(title))
		Popen([options.editor, file_name]).communicate()
	else:
		# wiki_text_path is an url
		edit_remote_wikipage(options.editor, wiki_text_path, title, 
				options.username, options.password, options.wiki)

if __name__ == '__main__':
	main()
