#!/usr/local/twc/bin/python

##=============================================================================
##
## Program :   domestic_rpt.py     
##
## Author  :   Chris Hill      
##
## Date    :   03/22/2003
##
## Purpose :   Generate Domestic Inventory Report for Intellistar
##
##=============================================================================

import sys
import os
import string
import twc.dsmarshal
from time import gmtime, strftime
import twc.DataStoreInterface
from omniORB import CORBA
from ftplib import FTP
import prov_utils

#-----------------------------------------------------------------------------
# Global Definitions                      
#-----------------------------------------------------------------------------

ds = twc.DataStoreInterface
dsmarshal = twc.dsmarshal

reportDirectory   = "/tmp"
reportFileName    = "domestic_istar.dat"

#this is intentionally a null string due to the chrooted scmt_prov dir
deliveryBaseDir   = ""
deliveryLogin, deliveryPass, deliveryHost = prov_utils.getScmtInfo()

#-----------------------------------------------------------------------------
# Main Program Logic                      
#-----------------------------------------------------------------------------

def main():


   ds.init()

   ##
   ## Get report time/date
   ##

   reportTime = strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())


   ##
   ## Open the output file and print the header
   ##

   try:
       fp = open(reportDirectory + "/" + reportFileName, "w")
   except:
       print "Error opening file <" + reportFileName + ">" 
       return 1
   
   fp.write('Intellistar/Domestic Inventory Report   ')
   fp.write(reportTime)
   fp.write('\n\n\n')
  
   
   ##
   ## Print the Identification Section of the report
   ##

   fp.write('[Identification]\n')

   headendId = ''
   headendId = getKey('headendId')

   starId = ''
   starId = getKeyVer('starId')

   expRev = ''
   expRev = getKey('expRev')

   mystruct = ''
   rc, mystruct = getStructKey('Cc_CurrentConditions')
   locName  = mystruct.locName[0] 

   fp.write('Primary Location Name..: ' + locName + '\n')
   fp.write('Headend ID.............: ' + headendId + '\n')
   fp.write('Star ID................: ' + starId + '\n')
   fp.write('Experience Revision....: ' + expRev + '\n\n\n')
   

   ##
   ## Print the Network Configuration Section         
   ##

   fp.write('[Network/BC Configuration]\n')

   bcConnectMethod = ''
   bcConnectMethod = getKeyVer('bcConnectMethod')

   bcIpAddress = ''
   bcIpAddress = getKeyVer('bcIpAddress')

   bcGateWay = ''
   bcGateWay = getKeyVer('bcGateWay')

   bcNetMask = ''
   bcNetMask = getKeyVer('bcNetMask')

   bcDnsSvr1 = ''
   bcDnsSvr1 = getKeyVer('bcDnsSvr1')

   bcDnsSvr2 = ''
   bcDnsSvr2 = getKeyVer('bcDnsSvr2')

   bcDialInNumber = ''
   bcDialInNumber = getKeyVer('bcDialInNumber')

   bcIspDialupLogin = ''
   bcIspDialupLogin = getKeyVer('bcIspDialupLogin')

   bcIspDialupNumber = ''
   bcIspDialupNumber = getKeyVer('bcIspDialupNumber')

   bcIspDialupPassword = ''
   bcIspDialupPassword = getKeyVer('bcIspDialupPassword')


   if bcConnectMethod == 'E':
       connectType = 'EtherNet' 
   else:
       connectType = 'Dialup' 

   fp.write('Network Type...........: ' + connectType + '\n')
   fp.write('IP Address.............: ' + bcIpAddress + '\n')
   fp.write('GateWay................: ' + bcGateWay + '\n')
   fp.write('Netmask................: ' + bcNetMask + '\n')
   fp.write('DNS 1..................: ' + bcDnsSvr1 + '\n')
   fp.write('DNS 1..................: ' + bcDnsSvr2 + '\n')
   fp.write('Local Dial In Number...: ' + bcDialInNumber + '\n')
   fp.write('ISP Dialup Number......: ' + bcIspDialupNumber + '\n')
   fp.write('ISP Dialup Login.......: ' + bcIspDialupLogin + '\n')
   fp.write('ISP Dialup Password....: ' + bcIspDialupPassword + '\n\n\n')


   ##
   ## Print the Primary met configuration stuff       
   ##

   fp.write('[Primary Met Configuration]\n')

   primZone = ''
   primZone = getKey('primaryZone')

   mystruct = ''
   rc, mystruct = getStructKey('Cc_CurrentConditions')
   primObs  = mystruct.obsStation[0] 
   secObs   = mystruct.obsStation[1] 
   primObsName  = mystruct.locName[0] 
   secObsName   = mystruct.locName[1] 

   mystruct = ''
   rc, mystruct = getStructKey('Fcst_ExtendedForecast')
   fcstPt   = mystruct.coopId 
   fcstName = mystruct.locName 

   mystruct = ''
   rc, mystruct = getStructKey('interestlist.county')
   primCounty = mystruct[0]      

   fp.write('Primary County.........: ' + primCounty + '\n')
   fp.write('Primary NWS Zone.......: ' + primZone + '\n')
   fp.write('Primary Obs Stations...: ' + primObs + ' (' + primObsName + ')\n')
   fp.write('Secondary Obs Stations.: ' + secObs + ' (' + secObsName + ')\n')
   fp.write('Forecast Point.........: ' + fcstPt + ' (' + fcstName + ')\n\n\n')


   fp.write("\n\n\nReport Complete");


   ##
   ## Close the file
   ##

   ds.uninit()
   fp.close()


   ##
   ## Send the File to the production Host
   ##

   sendReport(headendId)

   print 'Process completed successfully'

   return 0


#-----------------------------------------------------------------------------
# Generic key retrieval with config version
#-----------------------------------------------------------------------------

def getKeyVer(key):

    verKey = "configVersion"
    try:
        rc, dsval = ds.get([verKey])
    except:
        return  'x/a'
    else:
     
      ver = dsval[verKey]
      useKey = "Config." + ver + "." + key
 
      print useKey

      try:
          rc, dsval = ds.get([useKey])
      except:
          value = 'r/a'
      else:
          if dsval.has_key(useKey):
             value = dsval[useKey]
          else:
             value = 'n/a'
  
    return value

#-----------------------------------------------------------------------------
# Generic key retrieval with config version
#-----------------------------------------------------------------------------

def getKey(key):

      try:
          rc, dsval = ds.get([key])
      except:
          value = 'r/a'
      else:
          if dsval.has_key(key):
             value = dsval[key]
          else:
             value = 'n/a'

      return value
  

#-----------------------------------------------------------------------------
# Generic structure key retrieval. returns n/a' if error or key not found.
#-----------------------------------------------------------------------------

def getStructKey(key):

    rc = 0;

    verKey = "configVersion"
    try:
        rc, dsval = ds.get([verKey])
    except:
        return  'n/a'
    else:

      ver = dsval[verKey]
      useKey = "Config." + ver + "." + key
      print useKey
     
      try:
          dsval = dsmarshal.get(useKey)
      except:
          rc = 1
          dsval = ''    
  
    return rc, dsval
  

#-----------------------------------------------------------------------------
# Perform FTP of Report to Production Host
#-----------------------------------------------------------------------------

def sendReport(useHeadendId):

   fileToSend = reportDirectory + "/" + reportFileName
   destDirectory = deliveryBaseDir + "/" + useHeadendId
   storCommand = "STOR " + destDirectory + '/' + reportFileName

   os.chdir(reportDirectory)

   try:
       f = open(fileToSend, "r")
   except:
       print 'Error opening file <' + fileToSend + '>'
   else:
       try:
           ftp = FTP(deliveryHost)
           ftp.login(deliveryLogin,deliveryPass)
           ftp.storlines(storCommand, f) 
           ftp.quit()
           f.close
       except:
           print 'Error executing FTP <' + storCommand + '>'

   return 0


#-----------------------------------------------------------------------------
# Entry Point....
#-----------------------------------------------------------------------------

main()
