#! /usr/bin/env python
# _*_ coding: utf8 _*_
#
# Move page names of Clinton's executive orders
#
# run with args "-log -putthrottle:xx"
#
# Copyright (C) 2006, GrafZahl (en.wikisource.org user)
#
# Licence: GPLv2
#

import wikipedia

# Handle args

args = wikipedia.handleArgs()

for arg in args:
	print u'(WWW) Ignoring unrecognised argument: %s' % arg

# basic text tokens, etc.

oldbasename = u'Executive Order - %d'
newbasename = u'Executive Order %d'
baseoverwrite = u'{{subst:dated soft redirect|"[[%s]]"}}'
movesumm = u'[bot] removing dash from title'
oversumm = u'[bot] dated soft redirect'

# Start operation

site = wikipedia.getSite()
pagenos = range(12834, 13410)

for n in pagenos:
	# Render strings
	oldpagename = oldbasename % n
	newpagename = newbasename % n
	overwrite = baseoverwrite % newpagename
	# Step 1: Sanity checks on old page
	print u'(III) Performing sanity checks on page %s' % oldpagename
	page = wikipedia.Page(site, oldpagename)
	if not page.exists():
		print u'(III) Page %s does not exist, skipping' % oldpagename
		continue
	try:
		text = page.get()
	except wikipedia.Error:
		print u'(EEE) Error loading page %s, skipping' % oldpagename
		continue
	if (text.find(u'oft redirect') != -1):
		print u'(III) Page %s is already a soft redirect, skipping' % oldpagename
		continue
	# Step 2: Move old page to new name
	print u'(III) Moving %s to %s' % ( oldpagename, newpagename )
	wikipedia.put_throttle()
	if (page.move(newpagename, movesumm) == False):
		print u'(EEE) Page move FAILED!'
		continue
	# Step 3: Place soft redirect over old page
	print u'(III) Placing soft redirect over %s' % oldpagename
	page = wikipedia.Page(site, oldpagename)
	try:
		page.put(overwrite, oversumm, None, False)
	except wikipedia.Error:
		print u'(EEE) Placing soft redirect FAILED!'