#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2012, 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 java.io.IOException;

import com.urbancode.air.*
import com.urbancode.ubuild.codestation.client.*

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

System.setProperty("log4j.defaultInitOverride", "true")
LogManager.resetConfiguration()
Logger.getRootLogger().setLevel(Level.ERROR)
Logger.getRootLogger().addAppender(new ConsoleAppender(new PatternLayout("%m%n")))
Logger.getLogger("com.urbancode.ubuild.codestation").setLevel(Level.DEBUG)
Logger.getLogger("com.urbancode.vfs.client").setLevel(Level.INFO)

final def workDir = new File('.').canonicalFile
final def apTool = new AirPluginTool(this.args[0], this.args[1]);

final def props = apTool.getStepProperties();

final def projectName       = props['projectName']
final def workflowName      = props['workflowName']
final def buildLifeId       = props['buildLifeId']
final def codestationProjectName = props['codestationProjectName']
final def codestationBuildLifeId = props['codestationBuildLifeId']
final def buildLifeStamp    = props['buildLifeStamp']
final def buildLifeStatus   = props['buildLifeStatus']
final def buildLifeLabel    = props['buildLifeLabel']
final def artifactSetName   = props['artifactSetName']
final def permissions       = props['permissions']
final def useCache          = Boolean.valueOf(props['useCache'])

try {
    def url = System.getenv("WEB_URL")
    def authToken = System.getenv("AUTH_TOKEN")
    def userHomeDir  = new File(System.getProperty("user.home"))
    def cacheDir = new File(userHomeDir, ".codestation/cache")
    def credentials = AuthenticationCredentials.createAuthTokenCredentials(authToken)
    def codestationBaseUrl = url.endsWith("/") ? url + "rest2" : url + "/rest2"
    def codestationClient = new CodestationClient(codestationBaseUrl, credentials)
    
    if (useCache) {
        println "Using Codestation cache at ${cacheDir}"
        codestationClient.setCacheDir(cacheDir)
    }
    else {
        println "NOT using CodeStation cache"
    }
    
    if ("SET_ALL".equals(permissions)) {
        codestationClient.setSetPermissions(true)
    }
    else if ("SET_EXECUTE_ONLY".equals(permissions)) {
        codestationClient.setExecuteBitsOnly(true)
    }
    
    if (buildLifeId) {
        println "Downloading artifact set '${artifactSetName}' for project build life '${buildLifeId}'"
        def buildLife = codestationClient.buildLifeLookup.findBuildLife(buildLifeId)
        codestationClient.downloadArtifacts(buildLife, artifactSetName, workDir)
    }
    else if (codestationBuildLifeId) {
        println "Downloading artifact set '${artifactSetName}' for CodeStation build life '${codestationBuildLifeId}'"
        def buildLife = codestationClient.buildLifeLookup.findCodestationBuildLife(codestationBuildLifeId)
        codestationClient.downloadArtifacts(buildLife, artifactSetName, workDir)
    }
    else if (projectName && workflowName) {
        println "Downloading artifact set '${artifactSetName}' for the latest project build life with stamp '${buildLifeStamp ?: ''}', status '${buildLifeStatus ?: ''}', label '${buildLifeLabel ?: ''}'"
        def buildLife = codestationClient.buildLifeLookup.findLatestBuildLife(projectName, workflowName, buildLifeStamp, buildLifeStatus, buildLifeLabel)
        if (!buildLife) {
            throw new Exception("No project build life found with stamp '${buildLifeStamp ?: ''}', status '${buildLifeStatus ?: ''}', and label '${buildLifeLabel ?: ''}'")
        }
        println "Found build life '${buildLife.buildLifeId}' for build config '${projectName} - ${workflowName}'"
        codestationClient.downloadArtifacts(buildLife, artifactSetName, workDir)
    }
    else if (codestationProjectName) {
        println "Downloading artifact set '${artifactSetName}' for the latest CodeStation build life with stamp '${buildLifeStamp ?: ''}' and status '${buildLifeStatus ?: ''}'"
        def buildLife = codestationClient.buildLifeLookup.findLatestCodestationBuildLife(codestationProjectName, buildLifeStamp, buildLifeStatus)
        if (!buildLife) {
            throw new Exception("No CodeStation build life found with stamp '${buildLifeStamp ?: ''}' and status '${buildLifeStatus ?: ''}'")
        }
        println "Found build life '${buildLife.codestationBuildLifeId}' for CodeStation project '${codestationProjectName}'"
        codestationClient.downloadArtifacts(buildLife, artifactSetName, workDir)
    }
}
catch (IOException e) {
    String message = "An error occurred accessing the CodeStation Repository at " + System.getenv("WEB_URL") + ". It is " +
        "defined in the System - Server Settings page as the Agent External URL value. If this URL is incorrect, " +
        "please change it. Detailed error message: " + e.toString();
    throw new Exception(message, e);
}
catch (Exception e) {
    String message = "Error retrieving artifacts from CodeStation: " + e.toString();
    e.printStackTrace();
    throw new Exception(message, e);
}