#!/usr/bin/env groovy

import java.io.IOException;

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

import com.urbancode.commons.fileutils.filelister.FileListerBuilder.Directories;
import com.urbancode.commons.fileutils.filelister.FileListerBuilder.Permissions;
import com.urbancode.commons.fileutils.filelister.FileListerBuilder.Symlinks;
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 setName               = props['setName']
final def additionalHashes      = props['additionalHashes']?.tokenize(',')
final def symlinks              = Symlinks.valueOf(props['symlinks'] ?: "AS_LINK")
final def directories           = Directories.valueOf(props['directories'] ?: "INCLUDE_ALL")
final def permissions           = Permissions.valueOf(props['permissions'] ?: "NONE")
final def failIfNotFound        = Boolean.valueOf(props['failIfNotFound'])

try {
    def url = System.getenv("WEB_URL")
    def authToken = System.getenv("AUTH_TOKEN")
    def userHomeDir  = new File(System.getProperty("user.home"))
    def credentials = AuthenticationCredentials.createAuthTokenCredentials(authToken)
    def codestationBaseUrl = url.endsWith("/") ? url + "rest2" : url + "/rest2"
    def codestationClient = new CodestationClient(codestationBaseUrl, credentials)
    codestationClient.setFailIfNotFound(failIfNotFound)
    for (additionalHash in additionalHashes) { 
        codestationClient.addAdditionalDigestAlgorithm(additionalHash);
    }
    
    try {
        println "Uploading artifact set ${setName} to build life ${buildLifeId}"
        def buildLife = codestationClient.buildLifeLookup.findBuildLife(buildLifeId)
        codestationClient.uploadArtifactSet(buildLife, setName, workDir, symlinks, directories, permissions)
    }
    catch (ArtifactSetNotFoundException e) {
        println "Could not upload artifacts to artifact set $setName because the artifact set is not configured."
    }
}
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 (ArtifactUploadException e) {
    println e.getMessage()
    System.exit(1)
}
catch (Exception e) {
    String message = "Error uploading artifacts to CodeStation: " + e.toString();
    e.printStackTrace();
    throw new Exception(message, e);
}