#!/usr/bin/env ruby
require 'mediawikibot'

if ARGV.size() != 2
  $stderr.print($0 + " <wiki-user> <wiki-password>\n")
  exit(1)
end

#------------------------------------------------------------------------------
# TWiki stuff: specific things for our dirty wiki

$twiki_re = /^(Main|Termine|Wir) /

def is_twiki_link? (title)
  return title =~ $twiki_re
end

#------------------------------------------------------------------------------
# Rock!

b = MediaWikiBot::WikiBot.new("http://entropia.de/wiki/")
b.login(ARGV[0], ARGV[1])

allpages = b.get_allpages()
allpages.each do |title|
  $stderr.print("Processing '", title, "'\n")
  if is_twiki_link?(title) && b.is_redirect?(title)
    if b.is_not_linked?(title)
      b.delete(title, 
        "Old TWiki topic redirect and not linked anywhere in this wiki.")
    else
      b.get_what_links_here(title).each do |replace_where|
        b.replace(replace_where, title, get_redirect(title),
          "Old TWiki topic redirect, now fixed.")
      end
    end
  end
end