#!/usr/bin/python

# *******************************************************
# *  International Data Centre                          *
# *  Comprehensive Test Ban Treaty Organization         *
# *  Vienna                                             *
# *  Austria                                            *
# *******************************************************

## 
#  @author    Gerald Klinkl
# 
#  Script to convert binary file(s) to waveform. Requires
#  at least a binary file. If the script does not find 
#  clf files for the binary file it creates them using 
#  CD-Receiver in offline mode. Requires cdrecv and cd2wng
#  in PATH. Conversion is done in a temporary directory 

#  Revision 1.4  2014-08-20 GK
#  Improved error diagnostic if cd2wng binary is not in path
#  or if cd2wng stops unexpected
#
#  Revision 1.3  2011-09-27 08:29:44  ctbto
#  Fix typo
#
#  Revision 1.2  2011-03-02 15:41:16  gerald
#  Add new optional command line parameter sensor info file
#
#  Revision 1.1  2011-02-10 09:20:04  gerald
#  Add script for running cd2wng in batch mod
#
#  

from optparse import OptionParser
from datetime import *
from dateutil.relativedelta import *
import tempfile
import shutil
import sys
import os
import re

__version__ = "$Revision: 1.3 $"
version = "1.3"

# -----------------------------------------------------------------------------
# @short Initialize frame converter
#
# @description This function initializes the frame converter. It reads the 
# @description command line parameters and the configuration file and creates
# @description a dictionary containing name value pairs. In case of an
# @description error it stops the application
#
# @param none
#
# @return dictionary containing name value pairs
# -----------------------------------------------------------------------------

def initConverter():

   # define usage and allowed CLI parameters
   usage = "usage: %prog [options] file [file2 ...]"
   parser = OptionParser(usage)
   parser.add_option("-v", "--verbose",
                     action="store_true", dest="verbose", default=False,
                     help="print status messages to stdout")
   parser.add_option("-d", "--destination", dest="outDir", 
                     help="destination directory", metavar="DIR")
   parser.add_option("-s", "--starttime", dest="startTime", default = '',
                     help="report start time", metavar="YYYY/MM/DD")
   parser.add_option("-i", "--sensorinfo", dest="sensorFile", default = '',
                     help="sensor information file", metavar="FILE")

   # parse command line parameters
   (options, args) = parser.parse_args()

   if len(args) == 0:
      parser.error('no binary file provided')


   convParams = { 'Version': version }

   # Create Directory with all configuration parameters and command line
   # arguments
   convParams['args'] = args
   convParams['verbose'] = options.verbose
   convParams['outDir'] = options.outDir
   convParams['sensorFile'] = options.sensorFile
   convParams['rmOutDir'] = 'no'
   convParams['debugLevel'] = 1

   if not convParams['outDir']:
      convParams['outDir'] = tempfile.mkdtemp()
      convParams['rmOutDir'] = 'yes'
   elif not os.path.exists(convParams['outDir']):
      sys.exit("Error: '%s' does not exists" % convParams['outDir'])
      
   if not options.startTime:
      # if no start time is given, start time is taken from the binary file
      convParams['startTime'] = date(1900,1,1)
   else:
      try:
         st = options.startTime.split('/')
         debug(1, convParams, st)
         convParams['startTime'] = date(int(st[0]), int(st[1]), int(st[2]))
      except:
         sys.exit("Error: '%s' invalid start time" % options.startTime)

 
   return convParams

# -----------------------------------------------------------------------------
# @short Log debug message
#
# @description This function logs a debug message if the verbose flag
# @description is set
#
# @param reqDebugLevel   requested debug level
# @param cdqualParams    dictionary containing name value pairs
# @param debugMessage    Debug message
#
# @return nothing
# -----------------------------------------------------------------------------

def debug(reqDebugLevel, convParams, debugMessage):

   if reqDebugLevel <= int(convParams['debugLevel']):
      print >> sys.stderr, "(Debug%d): %s" % (int(convParams['debugLevel']), 
                                           debugMessage)


# -----------------------------------------------------------------------------
# @short Create config file if no one exists
#
# @description This function creates a config file if no one exists
#
# @return nothing
# -----------------------------------------------------------------------------

configLines = """port=7777
enableSyslog=NO
cdrecvIndexFilePath=./
filePath=./
strictModeEnable=NO
cd2wProductionLineFile=productionlines
refListStorePath=.
processMode=AS_ARRIVED
enableQualityCheck=YES
debugLevel=0
"""

def checkConfigFile():

   if os.path.exists('sensorInfo.txt'):
      checkFile('config.par', configLines + 'sensorFile=sensorInfo.txt\n')
   else:
      checkFile('config.par', configLines)

# -----------------------------------------------------------------------------
# @short Create production line file if no one exists
#
# @description This function creates a production line file if no one exists
#
# @return nothing
# -----------------------------------------------------------------------------

productionLine = """*;ALL;;;"""

def checkPLfile():

   checkFile('productionlines', productionLine)

# -----------------------------------------------------------------------------
# @short Create file if no one exists
#
# @description This function creates a file with a given file name and
# @description contents if the file name doesw not exists
#
# @param fileName      file name
# @param fileContent   file content
#
# @return nothing
# -----------------------------------------------------------------------------

def checkFile(fileName, fileContent):

   # Create config file if no one exists
   if not os.path.exists(fileName):
      # Create config file
      try:
          fp = open(fileName, "wb")
      except:
          sys.exit("Error: can't create '%s' for writing" % (fileName,))
      fp.write(fileContent)
      fp.close()


# -----------------------------------------------------------------------------
# @short Create index file
#
# @description This function creates an index file
#
# @param binFile      binary file name
#
# @return index file name
# -----------------------------------------------------------------------------

def appendIndexFile(binFile):

   cdProtVersion = '=cd1'
   if re.search('\.11bin$', binFile):
      cdProtVersion = '=cd11'

   fnp = binFile.split('.')
   indexFileName = '_7777.' + fnp[1] + '.idx'

   # create or append index file
   try:
       fp = open(indexFileName, "ab")
   except:
       sys.exit("Error: can't open '%s' for writing" % (indexFileName,))

   fp.write(re.sub('\.1[10]bin$', '', binFile) + cdProtVersion + '\n')
   fp.close()
   return indexFileName


# -----------------------------------------------------------------------------
# @short Create clf file out of binary file
#
# @description This function creates a clf file out of binary file
#
# @param binary file name
#
# @return nothing
# -----------------------------------------------------------------------------

def createClf(binFile, clfFile):

   # Create offline control file
   filename = 'offlinecontrol.txt'
   try:
       fp = open(filename, "wb")
   except:
       sys.exit("Error: can't create '%s' for writing" % (filename,))

   if re.search('\.11bin', binFile):
      cdversion = 'cd11'
   else:
      cdversion = 'cd10'

   # Write CD version
   fp.write(re.sub('\..*', '', binFile) + '=' + cdversion + '\n')
   # Write Cbin file name
   fp.write(binFile + '\n');
   fp.close()

   # Use receiver in offline mode to create clf files
   ret = os.system('cdrecv config.par offlinecontrol.txt')
   if ret:
       debug(1, convParams, "ret = %d\n" % (ret, ))
       sys.exit("Error: can't find cdrecv binary")

   # Open new clf file
   try:
       fpout = open(clfFile, "wb")
   except:
       sys.exit("Error: can't create '%s' for writing" % (clfFile,))

   # Open offline clf file(s)
   for clfFileOff in os.listdir('.'):

      if not re.search('.\clf_off$', clfFileOff):
         continue
      try:
          fpin = open(clfFileOff, "rb")
      except:
          sys.exit("Error: can't open '%s' for reading" % (clfFileOff,))

      try:
         line = fpin.next()
         while line:
            fpout.write(re.sub('_off', '', line))
            line = fpin.next()
      except:
         fpin.close()

      # Code above works only for one clf_off file. Without unlink
      # the previous clf files get merged into the current one when called
      # with more than one binary file
      os.unlink(clfFileOff)

   fpout.close()

# -----------------------------------------------------------------------------
# @short Close frame converter
#
# @description This function closes the frame converter. It cleans up
# @description the tempory files 
#
# @param configParams
#
# @return nothing
# -----------------------------------------------------------------------------

def closeConverter(convParams):

   if 'yes' == convParams['rmOutDir']:
      shutil.rmtree(convParams['outDir'])


def main():

   # Initialize waveform converter
   configParams = initConverter()

   # Check if the list of binary files is correct
   for binFile in configParams['args']:
      # check if the file exists and is readable
      if not os.access(binFile, os.R_OK):
         sys.exit("Error: '%s' does not exists or is not readable" % binFile)
      if not re.search('\.1[10]bin$', binFile):
         sys.exit("Error: '%s' is not a CD binary file" % binFile)

   # Populate temp directory
   for binFile in configParams['args']:
      # Link binary file into temp directory
      newFile = configParams['outDir'] + '/' + os.path.basename(binFile)
      if os.path.exists(newFile):
         sys.exit("Error: '%s' already exists" % newFile)
      os.symlink(os.path.abspath(binFile), newFile)

      # Link clf file into temp directory
      clfFile = re.sub('\.1[10]bin$', '.clf', binFile)
      if clfFile != binFile and os.path.exists(clfFile):
         # clf file found. link it 
         newFile = configParams['outDir'] + '/' + os.path.basename(clfFile)
         if os.path.exists(newFile):
            sys.exit("Error: '%s' already exists" % newFile)
         os.symlink(os.path.abspath(clfFile), newFile)

   # Link sensorInfo file if it does not exist                                                   
   if configParams['sensorFile']:
      newFile = configParams['outDir'] + '/' + 'sensorInfo.txt'
      if not os.path.exists(newFile):
         os.symlink(os.path.abspath(configParams['sensorFile']), newFile)

   # Change to temp directory
   saveDir = os.getcwd()
   os.chdir(configParams['outDir'])
   # Create a config file if no one exists in the output directory
   checkConfigFile()
   checkPLfile()

   idxFiles = {}
   # Check for clf files
   for binFile in configParams['args']:
      binFile = os.path.basename(binFile)
      clfFile = re.sub('\.1[10]bin$', '.clf', binFile)
      # if no clf file exists, create one
      if not os.access(clfFile, os.R_OK):
         createClf(binFile, clfFile)

      idxFiles[appendIndexFile(binFile)] = 1 # To get unique list

   startDate = date(1900,1,1)
   # Compute start and end date
   for idxFileAct in list(idxFiles.keys()):
      # compute end date as start date plus one day if not today
      # If today take current end date and time
      tpart = idxFileAct.split('.')
      sDate = date(int(tpart[1][0:4]), int(tpart[1][4:6]), int(tpart[1][6:8]))
      debug(1, configParams, sDate)

      if startDate == date(1900,1,1):
         startDate = sDate
         endDate = sDate
      elif startDate > sDate:
         startDate = sDate
      elif endDate < sDate:
         endDate = sDate

   if configParams['startTime'] == date(1900,1,1):
      tparam = "'%d/%02d/%02d 00:00:00' " % (startDate.year, \
                                             startDate.month, startDate.day)
   else:
      tparam = "'%d/%02d/%02d 00:00:00' " % \
         (configParams['startTime'].year, configParams['startTime'].month, \
          configParams['startTime'].day)

   if endDate == date.today():
      ut = datetime.utcnow()
      debug(1, configParams, ut)
      tparam = tparam + "'%d/%02d/%02d %02d:%02d:00'" % \
          (ut.year, ut.month, ut.day, ut.hour, ut.minute)
   else:
      # eDate = date(endDate.year, endDate.month, endDate.day)+relativedelta(days=+1)
      eDate = endDate + relativedelta(days=+1)
      debug(1, configParams, eDate)
      tparam = tparam + "'%d/%02d/%02d 00:00:00'" % \
          (eDate.year, eDate.month, eDate.day)

   debug(1, configParams, tparam)
   # run cd2wng in fixed interval file mode
   ret = os.system('type cd2wng 2>/dev/null')
   if ret:
       debug(1, configParams, "ret = %d\n" % (ret, ))
       sys.exit("Error: can't find cd2wng binary")

   ret = os.system('cd2wng config.par ' + tparam)
   if ret:
       debug(1, configParams, "ret = %d\n" % (ret, ))
       sys.exit("Error: cd2wng stopped unexpected")

   # copy files to output directory
   if 'yes' == configParams['rmOutDir']:
      for actFile in os.listdir('.'):
         if not re.search('.\mwf$', actFile) and \
            not re.search('.\qlr$', actFile) and \
            not re.search('.\wfdisc$', actFile):
            continue
         # rename might not work for different file systems
         shutil.copy2(actFile, saveDir + '/' + actFile)
         os.unlink(actFile)

   os.chdir(saveDir)
   # Run some clean up
   closeConverter(configParams)


if __name__ == "__main__":
  main()

