// This file provides tasks related to running commands on servers
// and copying files to/from those servers.

remotes {
    uitestbox {
        host = 'uitestbox'
        user = 'cuser'
        fileTransfer = 'scp'
    }
}

task runUiTestsOnUITestMachine {
    doLast {
        mkdir 'build/test-results/bdd_ui'
        ssh.runInOrder {
            session(remotes.uitestbox) {
                // following line will clear Zap's memory:
                execute "curl http://zap/JSON/core/action/newSession -s --proxy localhost:8888"
                // run the UI tests
                execute ". /etc/profile; cd demo_tests ; export DISPLAY=:0; ./gradlew runBehaveTests"
                // copy over the test results
                get from: "~/demo_tests/build/test-results/bdd_ui", into: "build/test-results/"
                get from: "~/demo_tests/build/bdd/behave_cucumber_style.json", into: "build/bdd/"
                // following line will generate a new report and store it at ~/zap_report.html
                execute "curl http://zap/OTHER/core/other/htmlreport --proxy localhost:8888 > ~/zap_report.html"
                // copy that report to our server
                get from: "~/zap_report.html", into: "build/reports/"
            }
        }
    }
}

// This runs the API tests by using SSH.  It does so on a remote server.
task runApiTestsOnUiTest {
    doLast {
        mkdir 'build/test-results/api_tests'
        ssh.runInOrder {
            session(remotes.uitestbox) {
                execute "cd demo_tests ; ./gradlew runApiTests"
                get from: '~/demo_tests/build/test-results/api_tests', into: 'build/test-results/'
            }
        }
    }
}

// This is for the virtual machine CentOS UI test box
// see also: deployToTestWindowsLocal, for when the CI/CD pipeline
// is on the local windows box of the teacher.
task deployToTest {
    doFirst {
        ssh.runInOrder {
            session(remotes.uitestbox)
                    {
                        put from: '/var/lib/jenkins/workspace/demo/build/libs/demo-1.0.0.war', into: '~/demo.war'
                        execute 'sudo mv demo.war /opt/tomcat/webapps/'
                        execute 'rm -fr demo_tests'
                        execute 'git clone cuser@jenkinsbox:~/demo demo_tests --branch master'
                        execute 'cd demo_tests;pipenv install 2>/dev/null'
                    }

        }
    }
    doLast {
        sleep 5 * 1000
    }
}
