#!/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.commons.httpclient.HttpClient
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 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")

try {
    def httpClient = new HttpClient()
    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, httpClient)
    for (additionalHash in additionalHashes) { 
        codestationClient.addAdditionalDigestAlgorithm(additionalHash);
    }
    
    println "Uploading all artifact sets to build life ${buildLifeId}"
    def buildLife = codestationClient.buildLifeLookup.findBuildLife(buildLifeId)
    codestationClient.uploadAllArtifacts(buildLife, workDir, symlinks, directories, permissions)
}
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 uploading artifacts to CodeStation: " + e.toString();
    e.printStackTrace();
    throw new Exception(message, e);
}