properties = null
def loadProperties() {
    node {
        properties = readProperties file: "${TESTGRID_HOME}/config.properties"
    }
}
pipeline {
    agent {
        node {
            label ""
             customWorkspace '/testgrid/testgrid-home/jobs/wso2is-5.3.0-LTS'
        }
    }
    environment {
        TESTGRID_NAME = 'WSO2-TestGrid'
        TESTGRID_HOME='/testgrid/testgrid-home'
        TESTGRID_DIST_LOCATION = '${TESTGRID_HOME}/testgrid-dist'

        PRODUCT="wso2is-5.3.0-LTS"

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

        INFRA_VERSION="5.4.0.1"
        INFRA_LOCATION="workspace/cloudformation-is-${INFRA_VERSION}"
        DEPLOYMENT_LOCATION="workspace/cloudformation-is-${INFRA_VERSION}"
        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 "Preparing TestGrid test-environment"
		        echo pwd()
                deleteDir()
                sh "mkdir workspace"
                // 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 branch: '5.3.0', 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 {
                            loadProperties()
                            def bucket= properties['AWS_S3_BUCKET_NAME']
                            if ( "${bucket}" == "null") {
                                bucket="unknown"
                            }
                            // Archive jtl files
                            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
            """

            // Archive artifacts
            script {
                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:"${bucket}", path:"artifacts/")
                }
            }
            // Delete logs and reports after upload
            dir("${TESTGRID_HOME}/${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'
       }
  }
}
