node('COMPONENT_ECS') {
    stage('Deploy to Dev'){
        deleteDir()
        copyArtifacts(projectName: 'testgrid/testgrid');
        sshagent(['testgrid-dev-key']) {
            sh """
                scp -o StrictHostKeyChecking=no web/target/*.war ${DEV_USER}@${DEV_HOST}:/testgrid/deployment/apache-tomcat-8.5.23/webapps/
                scp -o StrictHostKeyChecking=no distribution/target/*.zip ${DEV_USER}@${DEV_HOST}:/testgrid/jenkins-home/workspace/WSO2-TestGrid.zip
                """
           }
    }

    stage('Deploy to Prod'){
        def userInput
        mail (
            to: "${TEAM_MEMBERS},builder@wso2.org",
            subject: "Job '${env.JOB_NAME}' (${env.BUILD_NUMBER}) is waiting for input",
            body: "Hi team,\nLatest artifacts have been deployed to TestGrid-DEV." +
                "\nPlease do a round of tests and visit ${env.BUILD_URL} to approve/decline deploying to TestGrid-PROD." +
                "\nYou have 1 hour left!\n\nThanks!");
        try {
            timeout(time: 1, unit: 'HOURS') {
                userInput = input (
                        message: 'Deploy to Prod environment?', parameters: [
                        [$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this.']
                ])
            }
        } catch(err) { // input false
            userInput = false
            def user = err.getCauses()[0].getUser()
            echo ${user.toString}
            if('SYSTEM' == user.toString()) { // SYSTEM means timeout.
                echo "Aborted due to time-out."
            } else {
                echo "Aborted by: [${user}]"
            }
        }
        if (userInput == true) {
            sshagent(['testgrid-prod-key']) {
                sh """
                    scp -o StrictHostKeyChecking=no web/target/*.war ${PROD_USER}@${PROD_HOST}:/testgrid/deployment/apache-tomcat-8.5.24/webapps/
                    scp -o StrictHostKeyChecking=no distribution/target/*.zip ${PROD_USER}@${PROD_HOST}:/testgrid/jenkins-home/workspace/WSO2-TestGrid.zip
                 """
            }
        } else {
            echo "Not proceeding with pre prod"
        }
    }

}
