#!/usr/bin/env python
#
# Script that will move Insight testing results from /ftp/incoming to the
# appropriate location for dashboard summarization.
#
###

import cgi
import cgitb; cgitb.enable()

import re
import sys
import os

translation_table = {
 "CM-22-IRIX64-CC-Release": "zRel22-IRIX64-CC",
 "CM-22-OSF1-gcc-Release": "zRel22-OSF1-gcc",
 "CM-HEAD-IRIX64-CC-Release": "IRIX64-CC",
 "CM-HEAD-OSF1-gcc-Release": "OSF1-gcc",
 "CM-22-Darwin-gcc-Release": "zRel22-Darwin-gcc",
 "CM-HEAD-Darwin-gcc-Release": "Darwin-gcc",
 "Linux-2.4.18-24.8.0smp-c++": "Linux-g++",
}

def unencode(match):
 return "%c" % (int("0x%s" % match.group(1)))

def ReplaceString(str):
 for a in translation_table.keys():
   str = str.replace(a, translation_table[a])
 return str

def CopyFileWithReplace(srcname, dstname):
 dstname = ReplaceString(dstname)
 tmpname = "%s.tmp" % dstname
 try:
   # make directory
   dirname = os.path.dirname(dstname)
   if not os.path.exists(dirname):
     try:
       os.makedirs(dirname)
     except:
       print "Problem creating directory: %s" % dirname
       sys.exit(1)

   fpin = open(srcname, "r")
   fpout = open(tmpname, "w")
   while 1:
     data = fpin.read()
     if not data:
       break
     data = ReplaceString(data)
     fpout.write(data)
   os.rename(tmpname, dstname)
   os.remove(srcname)
 except:
   print "Problem copying file: %s" % srcname
   sys.exit(1)

def Trigger(destination, project, dropLocation = "/projects/FTP/incoming"):
 print "Content-type: text/plain"
 print ""

 form = cgi.FieldStorage()
 xmlfile = ""
 if form.has_key("xmlfile"):
   xmlfile = form["xmlfile"].value

 if not xmlfile:
   print "Sumbission file not specified"
   sys.exit(1)

 xmlfile = re.sub("\%(..)", unencode, xmlfile)
 if re.match("[^A-Za-z0-9_+.-]", xmlfile):
   print "Bad XML file name specified"
   sys.exit(1)

 fullPathToIncomingXMLFile = os.path.join(dropLocation, xmlfile)
 if not os.path.exists(fullPathToIncomingXMLFile):
   print "Cannot found file: %s" % xmlfile
   sys.exit(1)

 # file exists, so lets move it
 # first, translate the xml filename to a directory path
 xmlfile = re.sub("___", "/", xmlfile)

 # for security reasons, disallow any file with ".." in the user
 # specified path to keep people from storing files just anywhere in
 # the host directory structure
 if re.match("\.\.", xmlfile):
   print "Bad XML file name specified"
   sys.exit(1)

 # construct destination path and filename
 fullPathToDestinationXMLFile = os.path.join(destination, xmlfile)

 # make directory
 #dirname = os.path.dirname(fullPathToDestinationXMLFile)
 #if not os.path.exists(dirname):
 #  try:
 #    os.makedirs(dirname)
 #  except:
 #    print "Problem creating directory: %s" % dirname
 #    sys.exit(1)

 # now copy the file to destination
 try:
   #os.rename(fullPathToIncomingXMLFile, fullPathToDestinationXMLFile)
   CopyFileWithReplace(fullPathToIncomingXMLFile, fullPathToDestinationXMLFile)
 except:
   print "Problem triggering file: %s" % xmlfile
   sys.exit(1)

 if project in ("CMake", "Insight"):
   # Experimental CDash Stuff (CPR)
   if (project in ("Insight",)):
    import put
    f = open(fullPathToDestinationXMLFile, 'rb')
    put.putfile(f, 'http://ij.itk.org/CDash/submit.php?project=' + project,username="cdash",password="2pw4kw")
    f.close()
   # End CPR CDash

   import XMLRPCSubmit
   import TimeoutMethod
   TimeoutMethod.prepareTimeout()
   TimeoutMethod.timeoutMethod(XMLRPCSubmit.XMLRPCSubmitMethod,
                   ("http://dart.na-mic.org/%s/Command/" % project, fullPathToDestinationXMLFile, xmlfile),
                   200)
  
   #XMLRPCSubmit.XMLRPCSubmit("http://www.na-mic.org:8081/%s/Command/" % project, fullPathToDestinationXMLFile, xmlfile)
   #try:
   #  import xmlrpclib
   #
   #  server = xmlrpclib.ServerProxy("http://www.na-mic.org:8081/%s/Command/" % project)
   #  print server
   #
   #  try:
   #    fp = open(fullPathToDestinationXMLFile)
   #    content = fp.read()
   #    bin = xmlrpclib.Binary(content)
   #    print "Server responded: [%s]" % server.Submit.put(bin)
   #  except Exception, v:
   #    print "ERROR", v
   #    print "Unexpected error:", sys.exc_info()
   #    print "The file: \"%s\" content was:\n%s" % (fullPathToDestinationXMLFile, content)
   #except:
   #  print "Problem submitting XML-RPC for the file: %s" % xmlfile

 if project in ("kdeDart2Broken",):
   try:
     import xmlrpclib

     server = xmlrpclib.ServerProxy("http://public.kitware.com:8081/KDE/Command/")
     print server

     try:
       fp = open(fullPathToDestinationXMLFile)
       content = fp.read()
       bin = xmlrpclib.Binary(content)
       print "Server responded: [%s]" % server.Submit.put(bin)
     except Exception, v:
       print "ERROR", v
       print "Unexpected error:", sys.exc_info()
       print "The file: \"%s\" content was:\n%s" % (fullPathToDestinationXMLFile, content)
   except:
     print "Problem submitting XML-RPC for the file: %s" % xmlfile


 if fullPathToDestinationXMLFile[-3:] == ".gz":
   import gzip
   import shutil
   resname = fullPathToDestinationXMLFile[:-3]
   try:
     fp = gzip.open(fullPathToDestinationXMLFile)
     fr = open(resname, "w")
     shutil.copyfileobj(fp, fr)
     fp.close()
     fr.close()
     os.remove(fullPathToDestinationXMLFile)
   except:
     try:
       os.remove(resname)
     except:
       pass
     print "Problem uncompressing submission file"
     sys.exit(1)

 

 print "%s submission successful." % xmlfile

