def BUNDLE_PATH = '${WORKSPACE}/../cached_gems'
def CREDENTIALS = '7ce580c0-7d01-412f-bff1-485b4ca6196a'
def DOCKERFILE_PATH = 'testing-image'
def HOST_BUNDLE_PATH = '${HOME}/onapp-events/gems-3.0.5'
def RSPEC_RESULTS_PATH = 'rspec_results.xml'
def RSPEC_PROFILE_SPECS = '0'

pipeline {
    agent {
        dockerfile {
            dir("${DOCKERFILE_PATH}")
            args("""\
                -u root:root \
                -v ${HOST_BUNDLE_PATH}:${BUNDLE_PATH} \
            """)
        }
    }

    environment {
        BUNDLE_PATH = sh(script: "realpath ${BUNDLE_PATH}", returnStdout: true).trim()
        CREDENTIALS = "${CREDENTIALS}"
        RSPEC_PROFILE_SPECS = "${RSPEC_PROFILE_SPECS}"
        RSPEC_RESULTS_PATH = "${RSPEC_RESULTS_PATH}"
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '10', daysToKeepStr: '7'))
    }

    post {
        cleanup {
            cleanupWorkspace()
        }
    }

    stages {
        stage('Configure') {
            steps {
                startRedis()
                startRabbitMQ()
                populateKnownHosts('bitbucket.org')
                populateKnownHosts('github.com')
                configureBundler()
                bundleInstall()
            }
        }

        stage('Test') {
            post {
                always {
                    saveResults()
                }
            }

            steps {
                runSpecs()
            }
        }
    }
}

def bundleInstall() {
    sshagent(credentials: ["${CREDENTIALS}"]) {
        sh('''
            umask 0
            bundle install
        ''')
    }
}

def configureBundler() {
    sh('''
        umask 0
        bundle config jobs 8
    ''')
}

def cleanupWorkspace() {
    deleteDir()
    // additional cleanup required due to https://issues.jenkins.io/browse/JENKINS-41805
    dir("${WORKSPACE}@libs") {
        deleteDir()
    }
    dir("${WORKSPACE}@script") {
        deleteDir()
    }
    dir("${WORKSPACE}@tmp") {
        deleteDir()
    }
}

def populateKnownHosts(domain) {
    sh("""
        umask 0
        mkdir -p /root/.ssh
        ssh-keyscan ${domain} >> /root/.ssh/known_hosts
    """)
}

def runSpecs() {
    sh("""
        umask 0
        bundle exec rspec spec \
            --format progress \
            --format RspecJunitFormatter \
            --out ${RSPEC_RESULTS_PATH} \
            --deprecation-out /dev/null \
            --profile=${RSPEC_PROFILE_SPECS} \
            --backtrace
    """)
}

def saveResults() {
    archiveArtifacts(artifacts: "${RSPEC_RESULTS_PATH}", allowEmptyArchive: true)
    junit(testResults: "${RSPEC_RESULTS_PATH}", allowEmptyResults: true)
}

def startRabbitMQ() {
    sh('''
        umask 0
        rabbitmq-server -detached
    ''')
}

def startRedis() {
    sh('''
        umask 0
        redis-server --daemonize yes
    ''')
}
