#!/usr/bin/env ruby
require 'rubygems'
require 'open-uri'
require "fcgi"

FCGI.each_cgi do |cgi|
  cgi['redir'].match(/^(.*?)\/(.*?)\/(.*?)\.html/)
  from = Regexp::last_match[1]
  to = Regexp::last_match[2]
  page = Regexp::last_match[3].sub(" ","_")
  File.open("log",File::APPEND|File::WRONLY|File::CREAT) {|f|f.write "#{from}/#{to} - #{page}\n"}
  doc = open("http://#{from}.wikipedia.org/wiki/#{page}")
  webtext = doc.read
  if webtext.match(/\"interwiki-#{to}\"\>\<a href=\"(.*?)\">/)
    puts cgi.header( { 'Status' => '302 Moved', 'location' => Regexp::last_match[1] } )
  else
    puts cgi.header( { 'Status' => '302 Moved', 'location' => "http://#{from}.wikipedia.org/wiki/#{page}" } )
  end
end    

