#!/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 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 additionalHashes      = props['additionalHashes']
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")
// If requestTimeout is -1, system default value will be used
final def requestTimeout        = Integer.valueOf(props['requestTimeout'] ?: -1)

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)

    Helper helper = new Helper();
    List<String> additionalHashesList = helper.convertToList(additionalHashes);
    for (additionalHash in additionalHashesList) {
        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, requestTimeout)
}
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);
}