BUNDLER_VERSION = '2.1.4'

CREDENTIALS = '7ce580c0-7d01-412f-bff1-485b4ca6196a'

BUNDLE_PATH = '${WORKSPACE}/../cached_gems'
HOST_BUNDLE_PATH = '${HOME}/interface-dsl/gems-3.0.5'

DOCKERFILE_PATH = 'testing-image'
DOCKER_ARGS = """\
    -u root:root \
    -v ${HOST_BUNDLE_PATH}:${BUNDLE_PATH} \
"""

pipeline {
    agent any

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

    stages {
        stage('tests') {
            agent {
                dockerfile {
                    dir(DOCKERFILE_PATH)
                    args(DOCKER_ARGS)
                }
            }

            environment {
                BUNDLE_PATH = _runAndReturnStdout("readlink -f ${BUNDLE_PATH}")
            }

            post {
                cleanup {
                    cleanupWorkspace()
                }
            }

            steps {
                bundleInstall()
                runSpecs()
            }
        }
    }
}

def runSpecs() {
    def output = 'rspec_results.xml'

    try {
        bundleExec("""
            bundle exec rspec \
                --format progress \
                --format RspecJunitFormatter \
                --out ${output} \
                --profile 20 \
                --backtrace
        """)
    } finally {
        junit(testResults: output, allowEmptyResults: true, skipPublishingChecks: true)
    }
}

// GENERAL

def _run(String script) {
    sh("umask 0; ${script}")
}

def _runAndReturnStdout(String script) {
    sh(script: "umask 0; ${script}", returnStdout: true).trim()
}

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()
    }
}

// BUNDLER

def bundle(String command) {
    _run("bundle _${BUNDLER_VERSION}_ ${command.trim()}")
}

def bundleExec(String command) {
    bundle("exec ${command.trim()}")
}

def bundleInstall() {
    lock('bundle_install') {
        _run('''
            mkdir -p /root/.ssh
            ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts
            ssh-keyscan github.com    >> /root/.ssh/known_hosts
        ''')
        sshagent(credentials: [CREDENTIALS]) {
            bundle('install --jobs=8')
        }
    }
}
