# COPYRIGHT (C) ERICSSON RADIO SYSTEMS AB,  2008
#
# This script will perform "disk clean" activity.
# See Change Request WRNad58695 for more details.
#
# version 5, correction due to WRNad92539 (more files to be cleaned)
# version 6, correction due to WRNad93455 (inadequate response from coli handling)
# version 7, eeimphs (Michael Phillips)   Update to syntax to make the scrip runnable 
# version 8, eeimphs (Michael Phillips)   Removed the smocommandline.setPrompt("SMO#") as it is not currently 
#                                         used by SMO.
# version 9,  eeimphs  WRNad93455         Added the line individualFiles.append( "promp_place_holder" ) to cater for the current
#                                         current implementation of the deleteFiles() which uses the
#                                         len(filesArray)-1 notation to catter for from under normal condidtions.
#                                         als removed individualFiles.append( "/c/logfiles/CollectTraces.log" )
# version 10, eeimphs (Michael Phillips)  implemented cr WRNae25566, the script now attempts to deligate the disk 
#                                         clean to the node mo action RbsConfiguration.diskClean() if this fails it then falls
#                                         back on the origional smo script utility to perform the disk clean.
# 
# version 11, eeimphs WRNae40773          Fix for TR WRNae40773 adapted the use of CppUtils by means of traversing
#                                         down the Mo Topology tree.                               
#
# Author: eeimshn
#
#from smoscript_testbed import * (eeimphs) Used during test and devdlopment
from com.ericsson.nms.bss.sm.pyscript import InterfaceFactory
from com.ericsson.nms.bss.sm.pyscript import UnsupportedInterfaceVersionException

from java.lang import StringBuffer
from java.lang import String
from java.util import StringTokenizer


# Define functions
# Note, that main script is defined below

def cleanSelectedFolder( smoCommandLine, fldrName ):

   SMO.reportDetails('Cleaning folder ' + fldrName )
   
   receivedData = StringBuffer("")
   receivedData = smoCommandLine.send( "cd " + fldrName )

   strTemp = String( receivedData )
   strData = strTemp.toString()

   # dump cd result into log
   SMO.reportDetails( strData )

   # if folder exist
   if ( String( strData ).indexOf("No such file or directory") == -1):
      # because of TR WRNad93455, we can't trust that no_such_directory
      # was reported immediately, TR case shows that for some reason
      # it might be received in the next communication with command-line interface

      # get current directory
      receivedData = StringBuffer("")
      receivedData = smoCommandLine.send( "pwd" )
      strData = String( receivedData ).toString()

      # check 1. case WRNad93455
      if ( String( strData ).indexOf("No such file or directory") != -1):
          # do nothing, this directory does not exist
          SMO.reportDetails('TR WRNad93455 case, check 1, ignoring this directory ')
          return
  
      # check 2. pwd produces unexpected folder
      if ( String( strData ).indexOf("" + fldrName) == -1):
          # do nothing, current directory doesn't match target directory
          SMO.reportDetails('current directory doesnt match target directory, ignoring deletion of files ')
          return

      # list files
      receivedData = StringBuffer("")
      receivedData = smoCommandLine.send( "ls" )
      strData = String( receivedData ).toString()

      # check 3. double-checking case WRNad93455
      if ( String( strData ).indexOf("No such file or directory") != -1):
          # do nothing, target directory does not exist
          SMO.reportDetails('TR WRNad93455 case, check 3, ignoring this directory ')
          return

      # dump list of files into log
      SMO.reportDetails( strData )
      # and parse them into array
      filesInFolder = []
      # tokenize string with all possible EOL symbols
      st = StringTokenizer( strData, "\n\r" )
      # ignore the first line because it is emtpy line with padded spaces
      if ( st.hasMoreTokens() ):
          st.nextToken()
      # ignore the second line because it is directory name
      if ( st.hasMoreTokens() ):
          st.nextToken()
      # put individual file-names into array
      while (st.hasMoreTokens()):
          filesInFolder.append( st.nextToken() )
      # delete files
      deleteFiles( smoCommandLine, filesInFolder )
   else:
      SMO.reportDetails( 'Failed to cd into folder!!!' )

   return

def deleteFiles( smoCommandLine, filesArray ):
   from java.lang import StringBuffer
   from java.lang import String

   # -1 because last element in array is prompt $
   for i in range( len(filesArray)-1 ):
     fileName = filesArray[i]

     strTemp = String( fileName )
     if ( String( fileName ).endsWith("/") ):
        SMO.reportDetails("process subfolder")
        # recursive call
        # following call will cd into subfolder
        # and clean all contents
        cleanSelectedFolder( smoCommandLine, fileName )

     receivedData = StringBuffer("")
     receivedData = smoCommandLine.send( 'rm ' + fileName )
     strData = String( receivedData ).toString()
     # dump result into log, just in case there were
     # some problems
     SMO.reportDetails( strData )
   # end for cycle

   # return to parent directory
   # it is needed because of recursive calls, when processing subfolders
   # 'cd ..' will allow to get back to parent directory, and continue with
   # deletion of remaining files
   receivedData = StringBuffer("")
   receivedData = smoCommandLine.send( 'cd ..' )
   strData = String( receivedData ).toString()
   # dump result into log, just in case there were
   # some problems
   SMO.reportDetails( strData )

   return


# Method      : diskClean
# Description : This Method is called in the case the Node side mo RbsConfiguration.diskClean() action fails
#               as described by cr WRNae25566.
# Result      : Performs the Disck clean from the smo script side
# Author      : eeimphs (Michael Phillips)          
def diskClean() :
    SMO.reportTotal(13)

    SMO.reportCount(1)

    # Get the CommandLine interface
    SMO.reportDetails("Initialize command line connection")
    smoscript = smoif.getScriptUtils()

    smocommandline = smoscript.getCommandLineClient()
    
    # Connect to the node
    SMO.reportDetails("Connecting...")
    smocommandline.connect(SMO_NE_NAME,"$ ")
    # Removed this as this functionality is not in use by SMO (eeimphs)
    #smocommandline.setPrompt("SMO#")
    SMO.reportDetails("Ready for cleaning...")
    SMO.reportCount(2)
    
    cleanSelectedFolder( smocommandline, "/c/pmd" )
    SMO.reportCount( 3 )
    cleanSelectedFolder( smocommandline, "/c/logfiles/systemlog" )
    SMO.reportCount( 4 )
    cleanSelectedFolder( smocommandline, "/c/logfiles/dspdumps" )
    SMO.reportCount( 5 )
    cleanSelectedFolder( smocommandline, "/c/pi_data" )
    SMO.reportCount( 6 )
    cleanSelectedFolder( smocommandline, "/c/tmp" )
    SMO.reportCount( 7 )
    cleanSelectedFolder( smocommandline, "/c/usr" )
    SMO.reportCount( 8 )
    cleanSelectedFolder( smocommandline, "/c/logs" )
    SMO.reportCount( 9 )
    cleanSelectedFolder( smocommandline, "/c/public_html/cello/XML_files" )
    SMO.reportCount( 10 )
    cleanSelectedFolder( smocommandline, "/c/public_html/pi_data" )
    SMO.reportCount( 11 )
    
    # now for individual files, build array
    individualFiles = []
    # note that you can add more files using append statement as below
    individualFiles.append( "/c/logfiles/CollectTraces.log.zip" )
    #individualFiles.append( "/c/logfiles/CollectTraces.log" )
    individualFiles.append( "/c/logfiles/CollectTraces.log.gz" )
    
    # added this as the deleteFiles() method uses th -1 on the length of the passed 
    # in array to catter for the prompt (eeimphs)
    individualFiles.append( "promp_place_holder" )
    
    
    # pass array to defined function for deletion of set of files
    deleteFiles( smocommandline, individualFiles )
    SMO.reportCount( 12 )
    
    # disconnect from the node
    smocommandline.disconnect()
    SMO.reportDetails("Done!")
    SMO.reportCount(13)


# Main script starts here



# Everything that is printed to stdout/stderr will end up in a log file,
# which is available from the SMO GUI
#eeimphs replaced SMO.print("Log file for clean disk script WRNad58695, v.6, node " + SMO_NE_NAME)

SMO.reportDetails("Log file for clean disk script WRNad58695, v.6, node " + SMO_NE_NAME)

# Init the built-in interface. If the interface ever changes
# in an incompatible way this will throw an exception and
# thereby abort the script.

# Code below attempts to instantiate iface 1.3 (older version of SMO)
# some OSS-RC nodes might use version 1.4

# Update the interface according to document 4/1555-APR 901 0135 Uen
# Chapter 2.6.2

try:
  SMO.reportDetails("Get interface factory 1.5")
  smoif = InterfaceFactory('1.5')
except UnsupportedInterfaceVersionException:
  SMO.reportDetails("Get interface factory 1.4")
  smoif = InterfaceFactory('1.4')



try :
    SMO.reportDetails("Initializing CPP CORBA interaction.")
    cppUtils = smoif.getCppUtils()
    rootmo = cppUtils.getRootMoByNeName(SMO_NE_NAME)
    nodeb = rootmo.getChild("NodeBFunction")
    rbsConfigurationMo = nodeb.getChild("RbsConfiguration")
    SMO.reportDetails(" Attempting disk clean using node side RbsConfiguration.diskClean() action")
    rbsConfigurationMo.executeAction("diskClean", {})
# All exceptions both Java and Jyhton
except :
    import sys
    type, value, traceback = sys.exc_info()
    SMO.reportDetails("RbsConfiguration.diskClean() was unsuccessfull, reason : "+ str(value))
    SMO.reportDetails("smo_disc_clean script will perform the disk clean instead.")   
    diskClean()


