#!/usr/bin/python

import os, sys, re, datetime, ConfigParser, tempfile, urllib
from string import Template

if len(sys.argv) < 2:
  print "Usage: %s branch" % sys.argv[0]
  sys.exit()

config = ConfigParser.ConfigParser()
config.read(os.path.expanduser('~/.html5spec'))
if not config.has_section('html5'):
  print "Missing or incomplete %s" % os.path.expanduser('~/.html5spec')
  sys.exit()

branch = sys.argv[1]
today = datetime.date.today().strftime('%d %B %Y')

# get header, anolis flags from manu's repository
os.chdir(os.path.expanduser(config.get('html5', 'manu')))
os.system('git pull')
header = open('headers/header-w3c-html5').read()
header = header.replace('13 July 2009', today)
flags = re.search('ANOLIS_FLAGS="(.*)"', open('configure.ac').read()).group(1)

# get input source from git repository
os.chdir(os.path.expanduser(config.get('html5', 'source')))
os.system('git checkout ' + branch)
input = open('source').read()

# concat header and input
tempFD, tmpFile1 = tempfile.mkstemp('allspecs')
source = os.fdopen(tempFD, "w+")
source.write(header)
source.write(input)
source.close()

# remove anything that is not HTML5
tempFD, tmpFile2 = tempfile.mkstemp('html5spec')
cmd = Template(re.sub(r'\n\s+', ' ', """
  perl -e '$$_ = join("", <>); 
    s/<!--END html5-->.*?<!--START html5-->//gs;
    s/<!--(START|END).*?-->//g;
    print' $tmpFile1 >$tmpFile2
""")).substitute(locals()).strip()
print cmd; os.system(cmd)
os.remove(tmpFile1)

# read annotations
tempFD, tmpFile3 = tempfile.mkstemp('annotations')
annotations = os.fdopen(tempFD, "w+")
annotations.write(urllib.urlopen('http://pimpmyspec.net/aquarium.py/annotations/output?spec_status=WD&annotations_url=http://www.whatwg.org/specs/web-apps/current-work/status.cgi%3Faction%3Dget-all-annotations&tracker_url=http://www.w3.org/html/wg/tracker/').read())
annotations.close()

# execute Anolis
os.chdir(os.path.expanduser(config.get('html5', 'w3c')))
output=os.path.join(branch, 'fullspec.html')
flags = flags + ' --annotations ' + tmpFile3 + ' --annotate-w3c-issues'
cmd= 'anolis %s %s %s' % ( flags, tmpFile2, output )
print cmd; os.system(cmd)
os.remove(tmpFile2)
os.remove(tmpFile3)

# split the spec
cmd = 'python spec/tools/spec-splitter.py --w3c %s %s' % (output, branch)
print cmd; os.system(cmd)

# oddly, Overview is supposed to be the full spec, so let's fix that
spec = os.path.join(branch, 'spec.html')
overview = os.path.join(branch, 'Overview.html')
if os.path.exists(spec): os.remove(spec)
os.rename(overview, spec)
os.rename(output, overview)

