#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import re
import random
import subprocess
import cgi
#import cgitb; cgitb.enable()
import platform

# generate hxml file used to compile swf file
def genHxmlFile( xmlfile, swffile, hxmlfile ):
  fh = open( hxmlfile, "w" )
  fh.write( "-cp tinylib\n" )
  fh.write( "-cp pdb\n" )
  fh.write( "-swf " + swffile + "\n" )
  fh.write( "-swf-version 9\n" )
  fh.write( "--flash-strict\n" )
  fh.write( "-main Main\n" )
  fh.write( "-swf-version 11.2\n" )
  fh.write( "-lib format\n" )
  fh.write( "-resource " + xmlfile + "@structure\n" )
  fh.close()

def genSwfFile( wm3dsrcdir, hxmlfile ):
  haxe = "/usr/bin/haxe"
  cmdline = [haxe, hxmlfile]
  subprocess.call( cmdline, cwd=wm3dsrcdir )

# generate random filename (for write)
# return value is [ filehandle, filename ]
def getNewFile( workdir, filename, extension ):
  while(True):
    fn = workdir + filename + str(random.randint( 0, 32767 )) + extension
    # there may be race condition...
    if os.path.exists( fn ):
      continue
    fh = open( fn, "w" )
    return [ fh, fn ]

if __name__ == "__main__":
  # you need to specify home directory of the user,
  # because haXe seems to use this environmental value implicitly.
  os.environ['HOME'] = "/home/www-data"
  saveonly = False
  inputdata = ""
  workdir = "/tmp/"
  wm3dsrcdir = "/home/kamo/haXe/wm3d/src"

  form = cgi.FieldStorage()
  inputdata = str( form.getvalue( "XMLdata" ) )
  if "savexml" in form:
    saveonly = True

  # do nothing. quit. empty page will be returned?
  if inputdata == "":
    # write empty file
    print "Content-Type:application/octet-stream;"
    print "Content-Disposition: attachment; filename=\"watermelon.xml\"\n"
    sys.exit(0)

  if not saveonly:
    # save xml data to outputxml file
    [ fh, outputxml ] = getNewFile( workdir, "watermelon", ".xml" )
    fh.write( inputdata )
    fh.close()
    # generate hxml file on workdir to compile into swf file
    hxmlfile = re.sub( r'\.xml$', '.hxml', outputxml )
    outputswf = re.sub( r'\.xml$', '.swf', outputxml )
    genHxmlFile( outputxml, outputswf, hxmlfile )
    genSwfFile( wm3dsrcdir, hxmlfile )

  if saveonly:
    # filename is dummy
    print "Content-Type:application/octet-stream;"
    print "Content-Disposition: attachment; filename=\"watermelon.xml\"\n"
    print inputdata,
  else:
    print "Content-Type: application/octet-stream;"
    print "Content-Disposition: attachment; filename=\"watermelon.swf\"\n"
    fh = open( outputswf, "rb" )
    print fh.read()
    fh.close()
    if os.path.isfile( outputxml ):
      os.remove( outputxml )
    if os.path.isfile( hxmlfile ):
      os.remove( hxmlfile )
    if os.path.isfile( outputswf ):
      os.remove( outputswf )
