#!/u/eddemaine/bin/python
# NOTE 1: You should also symlink psnotes.py to psnotes-redirect.py
#         so that problem-session notes are also redirected.
# NOTE 2: To get ps, pdf, ps.gz, etc. files redirecting correctly, you need to
#         add the following to your .htaccess file:
# AddType text/html .gz
# AddType text/html .Z
# AddType text/html .zip
# AddType text/html .ps
# AddType text/html .pdf

import glob, os, re, sys

webdir = os.path.join (os.environ["HOME"], "public_html/")
target_base_url = "http://db.uwaterloo.ca/~eddemain/"
file_re = r"\.(html|ps|pdf|tar|fig|eps)(\.(gz|Z|zip))?$"
file_rec = re.compile (file_re)
backup_suffix = "!"
redirection_re = "<!--This file was automagically generated by redirect_everything, written by Erik Demaine-->"
redirection_rec = re.compile (redirection_re)

def redirect_dir (junk, dir, files):
  for file in files:
    if not file_rec.search (file): continue
    fullfile = os.path.join (dir, file)
    print fullfile
    if os.path.exists (fullfile + backup_suffix):
      if not redirection_rec.search (open (fullfile, "r").read ()):
        print "%s and %s! exist, yet the former does not appear to be a redirection!" % (fullfile, fullfile)
        sys.exit (1)
    else:
      os.rename (fullfile, fullfile + backup_suffix)
    assert fullfile[:len (webdir)] == webdir
    offset = fullfile[len (webdir):]
    new_url = target_base_url + offset
    if new_url[-11:] == "/index.html": new_url = new_url[:-10]
    out = open (fullfile, "w")
    out.write ("""<HTML>
<HEAD>
<TITLE>301 Moved Permanently</TITLE>
<META HTTP-EQUIV="refresh" content="10;URL=%s">
</HEAD>
<BODY>
<H1>301 Moved Permanently</H1>
<A HREF="%s">Erik Demaine's webpage</A>
has moved to a new server.
The page you were referring to now has URL
<CODE><A HREF="%s">%s</A></CODE>.
On most browsers, you will be brought there in 10 seconds.
<P>
Please change your links, because the old server will go down in a couple
of months. <BR>
(Otherwise I would have used a true 301/RedirectPermanent.)
<P>
Thanks!  &nbsp; &nbsp; &nbsp; - Erik
%s
</BODY>
</HTML>""" % (new_url, target_base_url, new_url, new_url, redirection_re))
    out.close ()
    os.chmod (fullfile, 0644)

os.path.walk (webdir, redirect_dir, None)
