#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import java.util.UUID

import com.urbancode.air.AirPluginTool
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder
import com.ibm.uclab.csrepl.client.CodestationClient
import com.ibm.uclab.csrepl.client.ops.Verify
import com.ibm.uclab.csrepl.http.HttpClientWrapper

import org.apache.log4j.BasicConfigurator
import org.apache.log4j.ConsoleAppender
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout

def apTool = new AirPluginTool(args[0], args[1])

def AGENT_HOME = new File(System.env['AGENT_HOME'])
def PROXY_HOST = System.env['PROXY_HOST']
def PROXY_PORT = System.env['PROXY_PORT']
if (PROXY_PORT != null) {
    PROXY_PORT = Integer.valueOf(PROXY_PORT)
}
def CODESTATION_URL = System.env['CODESTATION_URL']
def CODESTATION_USE_PROXY = Boolean.valueOf(System.env['CODESTATION_USE_PROXY'])

def props = new Properties();
def inputPropsFile = new File(args[0]);
inputPropsFile.withInputStream {
    props.load(it);
}

def serverURL = props['serverUrl']
def versionId = UUID.fromString(props['versionId'])
def directoryOffset = props['directoryOffset']
def fileIncludePatterns = props['fileIncludePatterns']
def fileExcludePatterns = props['fileExcludePatterns']

def baseDirectory
if (directoryOffset) {
    baseDirectory = new File(directoryOffset).canonicalFile
}
else {
    baseDirectory = new File('.').canonicalFile
}

def includes = fileIncludePatterns?.readLines()
def excludes = fileExcludePatterns?.readLines()

//
// Validation
//
if (baseDirectory.isFile()) {
    throw new IllegalArgumentException("Base directory ${baseDirectory} is a file!")
}

//
// Configure logging
//
def configureLogging = {
    BasicConfigurator.resetConfiguration()

    def layout = new PatternLayout("%m%n")
    def appender = new ConsoleAppender(layout)
    Logger.getRootLogger().addAppender(appender)
    
    Logger.getRootLogger().setLevel(Level.WARN)
    Logger.getLogger("httpclient.wire.content").setLevel(Level.OFF)
    Logger.getLogger("com.ibm.uclab.csrepl.client.ops").setLevel(Level.INFO)
}
configureLogging()

//
// Download the files
//
def getCodestationClient = {
    def url = CODESTATION_URL
    if (url == null) {
        url = serverURL
    }
    while (url.endsWith("/")) {
        url = url.substring(0, url.length - 1)
    }
    def builder = new HttpClientBuilder()
    if (PROXY_HOST) {
        if (!CODESTATION_URL || CODESTATION_USE_PROXY) {
            builder.setProxyHost(PROXY_HOST)
            builder.setProxyPort(PROXY_PORT)
        }
    }
    builder.setUsername(apTool.getAuthTokenUsername())
    builder.setPassword(apTool.getAuthToken())

    String verifyServerIdentityString = System.getenv().get("UC_TLS_VERIFY_CERTS");
    Boolean trustAllCerts = Boolean.valueOf(verifyServerIdentityString);
    builder.setTrustAllCerts(!trustAllCerts);

    builder.setPreemptiveAuthentication(true)
    def httpClient = builder.buildClient()
    def wrapper = new HttpClientWrapper(httpClient)
    def csc = new CodestationClient(url, wrapper)
    csc.start()
    return csc
}
def csClient = getCodestationClient()

def op = new Verify(csClient, baseDirectory, versionId)
op.setIncludes(includes)
op.setExcludes(excludes)
op.setSlowVerification(true)

println "Artifact source: ${csClient.url}"
println "Verifying files in ${baseDirectory}"
println "Including ${fileIncludePatterns}"
println "Excluding ${fileExcludePatterns}"

op.run()

if (op.failureCount > 0) {
    System.exit 1
}
else {
    println "All files match."
    System.exit 0
}
