properties = null
def loadProperties() {
    node {
        properties = readProperties file: "${TESTGRID_HOME}/config.properties"
    }
}
pipeline {
    agent {
        node {
            label ""
             customWorkspace '/testgrid/testgrid-home/jobs/wso2is-5.4.1-LTS'
        }
    }

    environment {
        TESTGRID_NAME = 'WSO2-TestGrid'
        TESTGRID_DIST_LOCATION = '/testgrid/testgrid-home/testgrid-dist'
        TESTGRID_HOME='/testgrid/testgrid-home'

        PRODUCT="wso2is-5.4.1-LTS"

        INFRASTRUCTURE_REPOSITORY='https://github.com/harshanL/cloudformation-is'
        DEPLOYMENT_REPOSITORY='https://github.com/harshanL/cloudformation-is'
        SCENARIOS_REPOSITORY='https://github.com/wso2-incubator/identity-test-integration.git'

        INFRA_LOCATION="workspace/aws-cloudformation-templates"
        DEPLOYMENT_LOCATION="workspace/aws-cloudformation-templates"
        SCENARIOS_LOCATION="workspace/identity-test-integration"
        INFRA_CONFIGS_LOCATION="${INFRA_LOCATION}/infrastructure-build-plans"

        AWS_ACCESS_KEY_ID=credentials('AWS_ACCESS_KEY_ID')
        AWS_SECRET_ACCESS_KEY=credentials('AWS_SECRET_ACCESS_KEY')
        tomcatUsername=credentials('TOMCAT_USERNAME')
        tomcatPassword=credentials('TOMCAT_PASSWORD')
        PWD=pwd()
        JOB_CONFIG_YAML = "job-config.yaml"
        JOB_CONFIG_YAML_PATH = "${PWD}/${JOB_CONFIG_YAML}"
    }

    tools {
        jdk 'jdk8'
    }

    stages {
        stage('Preparation') {
            steps {
                    echo pwd()
                    deleteDir()

                    // Clone scenario repo
                    sh "mkdir -p ${SCENARIOS_LOCATION}"
                    dir("${SCENARIOS_LOCATION}"){
                        git url: "${SCENARIOS_REPOSITORY}"
                    }

                    // Clone infra repo
                    sh "mkdir -p ${INFRA_LOCATION}"
                    dir("${INFRA_LOCATION}"){
                        git url:"${INFRASTRUCTURE_REPOSITORY}"
                    }

                    sh """
                    echo 'jobName: ${PRODUCT}' >> ${JOB_CONFIG_YAML_PATH}
                    echo 'infrastructureRepository: ${INFRA_LOCATION}/cloudformation-templates/pattern-1/' >>${JOB_CONFIG_YAML_PATH}
                    echo 'deploymentRepository: ${INFRA_LOCATION}/cloudformation-templates/pattern-1/' >> ${JOB_CONFIG_YAML_PATH}
                    echo 'scenarioTestsRepository: ${SCENARIOS_LOCATION}' >> ${JOB_CONFIG_YAML_PATH}
                    echo 'testgridYamlLocation: ${INFRA_CONFIGS_LOCATION}/single-node-infra.yaml' >> ${JOB_CONFIG_YAML_PATH}

                    echo The job-config.yaml:
                    cat ${JOB_CONFIG_YAML_PATH}
                    """

                    stash name: "${JOB_CONFIG_YAML}", includes : "${JOB_CONFIG_YAML}"

                    sh """
                    cd ${TESTGRID_HOME}/testgrid-dist/${TESTGRID_NAME}
                    ./testgrid generate-test-plan \
                        --product ${PRODUCT} \
                        --file ${JOB_CONFIG_YAML_PATH}
                    """
            }
        }

        stage('test-plan-run') {
            steps {
                script {
                    for (f in findFiles(glob: '**/test-plans/*.yaml')) {
                        try {
                            echo 'Running Test-Plan'
                            sh "java -version"
                            unstash name: "${JOB_CONFIG_YAML}"
                            sh """
                            cd ${SCENARIOS_LOCATION}
                            git clean -f
                            cd ${TESTGRID_HOME}/testgrid-dist/${TESTGRID_NAME}
                            ./testgrid run-testplan --product ${PRODUCT} \
                            --file "${PWD}/test-plans/${f.name}"
                            """
                        } catch (Exception err) {
                            echo "Error : ${err}"
                            currentBuild.result = 'FAILURE'
                        }
                        echo "RESULT: ${currentBuild.result}"
                         script {
                            // Archive jtl files
                            loadProperties()
                            def bucket= properties['AWS_S3_BUCKET_NAME']
                            if ( "${bucket}" == "null") {
                                bucket="unknown"
                            }

                            withAWS(credentials:'TESTGRID_BOT_CREDENTIALS') {
                                // Upload artifacts to S3
                                s3Upload(workingDir:"${TESTGRID_HOME}", includePathPattern:"**/*.jtl", bucket:"${bucket}", path:"artifacts/")
                            }
                        }
                    }
                }
            }
        }
    }



    post {
        always {
           sh """
            cd ${TESTGRID_HOME}/testgrid-dist/${TESTGRID_NAME}
            ./testgrid finalize-run-testplan \
            --product ${PRODUCT} --workspace ${PWD}
            """

           sh """
             cd ${TESTGRID_HOME}/testgrid-dist/${TESTGRID_NAME}
            ./testgrid generate-report \
            --product ${PRODUCT} \
            --groupBy scenario
            """
            script {
                 // Archive artifacts
                loadProperties()
                def bucket= properties['AWS_S3_BUCKET_NAME']
                if ( "${bucket}" == "null") {
                    bucket="unknown"
                }
                withAWS(credentials:'TESTGRID_BOT_CREDENTIALS') {
                  // Upload artifacts to S3
                  s3Upload(workingDir:"${TESTGRID_HOME}", includePathPattern:"**/*.log, **/*.html", bucket:"jenkins-testrun-artifacts", path:"artifacts/")
                }
            }

            // Delete logs and reports after upload
            dir("${TESTGRID_HOME}/jobs/${PRODUCT}") {
                sh """
                find . -maxdepth 1 -type f \\( -name "*.log" -o -name "*.html" \\) -delete
                """
            }

//              emailext body: '''$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS:

// Check console output at $BUILD_URL to view the results.''', subject: '$PROJECT_NAME - Build # $BUILD_NUMBER - $BUILD_STATUS!', to: 'harshan@wso2.com,kasung@wso2.com,asmaj@wso2.com,viduran@wso2.com,sameeraw@wso2.com,pasinduj@wso2.com'

    }
  }
}
