/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

import com.urbancode.air.AirPluginTool

AirPluginTool airTool = new AirPluginTool(args[0], args[1])
Properties props = airTool.getStepProperties()
def workDir = new File('.').canonicalFile

def checkSubfolder = props['checkSubfolder'].toBoolean()
def checkCustomDir = props['checkCustomDir'].toBoolean()

def arg = new String[2]
arg[0] = props['file'].trim()

if(checkCustomDir==false){
   arg[1] = workDir.getPath()
}
else{
   arg[1] = props['dir'].trim()
}

def totalPath = arg[1] + "/" + arg[0]

if (arg.length < 2)
{
   println "Need to specify directory to be searched and the substring of file."
   println "\tUSAGE: fileFind <directoryPath> <fileNameSubString>"
   System.exit(-1)
}


def directoryName = arg[1]
def fileSubStr = arg[0]
def filePattern = ~/${fileSubStr}/
def directory = new File(directoryName)

if (!directory.isDirectory())
{
   println "The provided directory name ${directoryName} is NOT a directory."
   System.exit(-2)
}
println "Searching for files including ${fileSubStr} in directory ${directoryName}..."


def count = 0

def findFileWithoutSubString =
{  
   if (filePattern.matcher(it.name).find())
   {
      if(it.path==totalPath){
         println "\t${it.name} (size :--> ${it.size()})  (Path :--> ${it.path})"
         count=count+1
      }
      
   }
}


def findFileWithSubString =
{  
   if (filePattern.matcher(it.name).find())
   {
      
      println "\t${it.name} (size :--> ${it.size()})  (Path :--> ${it.path})"
      count=count+1
   }
}

if(checkSubfolder==false)
{

   println "Matching Files:"
   directory.eachFileRecurse(findFileWithoutSubString)


   if(count==1)
   {
      println " \n \t 1  File/Folder found with matching name."
   }
   else if (count>1)
   {
      println "\n \t ${count}  Files/Folders found with matching name"
   }
   else
   {
      println "\n \t  NO matching File/Folder found"
   }

   System.exit(0)   
}


else
{
   println "Matching Files:"
   directory.eachFileRecurse(findFileWithSubString)


   if(count==1)
   {
      println " \n \t 1  File/Folder found with matching name."
   }
   else if (count>1)
   {
      println "\n \t ${count}  Files/Folders found with matching name"
   }
   else
   {
      println "\n \t  NO matching File/Folder found"
   }

   System.exit(0)

   
}
