#!/usr/bin/env groovy

import java.io.IOException;

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

import org.apache.http.client.HttpClient
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

BasicConfigurator.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 url               = props['ubuildUrl']
final def username          = props['ubuildUser']
final def password          = props['ubuildPassword']
final def projectName       = props['projectName']
final def workflowName      = props['workflowName']
final def buildLifeId       = props['buildLifeId']
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']

try {
    
    def userHomeDir  = new File(System.getProperty("user.home"))
    def cacheDir = new File(userHomeDir, ".codestation/cache")
    def credentials = AuthenticationCredentials.createUsernamePasswordCredentials(username, password)
    def codestationBaseUrl = url.endsWith("/") ? url + "rest2" : url + "/rest2"
    def codestationClient = new CodestationClient(codestationBaseUrl, credentials)
    codestationClient.setCacheDir(new File(System.getProperty("user.home")))
    
    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 (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)
    }
}
catch (IOException e) {
    String message = "An error occurred accessing the Codestation Repository at ${url}."
    throw new Exception(message, e);
}
catch (Exception e) {
    String message = "Error retrieving artifacts from Codestation: " + e.toString();
    e.printStackTrace();
    throw new Exception(message, e);
}