/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2002-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
*/

package com.urbancode.air.plugin.iisconfiguration
import groovy.io.FileType

class Util{
    //format the web deploy command correctly according to resource role type
    static Map formatPathAndTypeFromResourceRoleName(String resourceRoleName, String resourcePath){
        def type = ""
        def path = ""
        def resultMap = [:]
        def parentName = (resourcePath =~ /.*\/(.*)/)[0][1].trim()
        if (resourceRoleName == Globals.ROOT_ROLE_NAME){
            type = "webServer"
            path = ""
        }
        else if (resourceRoleName == Globals.SITE_ROLE_NAME){
            type = "appHostConfig"
            path = parentName
        }
        else if (resourceRoleName == Globals.APP_POOL_ROLE_NAME){
            type = "appPoolConfig"
            path = parentName
        }
        else if (resourceRoleName == Globals.APP_ROLE_NAME){
            type = "appHostConfig"
            path = (resourcePath =~ /Sites\/(.*)/)[0][1].trim()
        }
        else {
            throw new Exception("Unrecognized resource role: ${resourceRoleName}. Unable to process request.")
        }

        resultMap['type'] = type
        resultMap['path'] = path

        return resultMap
    }

    //search for a file by name and return the reference to that file
    static File findFileRecursivelyByName(String nameToSearchFor) {
        def files
        def parentDir = new File(".")
        def foundFile = "FILE NOT FOUND"
        parentDir.eachFileRecurse (FileType.FILES) { file ->
            if (file.toString().contains(nameToSearchFor)) {
                foundFile = file
                return
            }
        }

        return foundFile
    }

}
