#!/usr/bin/env python
import os
import cgi
import sys
import os.path
import jinja2

result = {}
try:
    form = cgi.FieldStorage()
    unique_filename = form.getvalue("download")
    TEMP_FOLDER = os.path.join(os.getcwd(), 'temp')
    PROJECT_LOCATION=os.path.join(os.getcwd(), 'cgi-bin')
    mypath = os.path.join(TEMP_FOLDER, unique_filename)
    if os.path.isfile(mypath):
        statinfo = os.stat(os.path.join(TEMP_FOLDER, unique_filename))
        filesize = statinfo.st_size
        print 'Content-Type: application/octet-stream'
        print 'Content-Disposition: attachment; filename="scene.sif"'
        #print 'Content-Length: ' + str(filesize)
        print
        f = open(os.path.join(TEMP_FOLDER, unique_filename), 'rb')
        while True:
            data = f.read(4096)
            sys.stdout.write(data)
            if not data:
                break
        os.unlink(os.path.join(TEMP_FOLDER, unique_filename))
    else:
        templateLoader = jinja2.FileSystemLoader(searchpath=PROJECT_LOCATION)
        templateEnv = jinja2.Environment(loader=templateLoader)
        TEMPLATE_FILE = os.path.join('cgi-bin','error.html')
        template = templateEnv.get_template( TEMPLATE_FILE)
        outputText = template.render()
        print outputText
except Exception as e:
    result['success'] = False
finally:
    pass
