@Library('jenkins-common') _

utils.initProperties()

def appName        = 'pg_searchable'

def databaseName  = 'pg_searchable'
def databaseHost  = 'localhost'
def databasePort  = '5432'
def databasePool  = '10'
def databaseUser  = 'postgres'
def databasePass  = 'Q99d5Aikh2VR'
def nexusUser     = 'jenkins'
def nexusPass     = 'ASTrIAnDIdEONVan'

utils.onNode(nodeLabel: 'ubuntu-ruby-215') {
    String version

    version = utils.stagesGitCheckout()

    stage('Save version') {
        writeFile file: 'VERSION', text: version
    }

    stage('Run tests') {
        withEnv([
            "DATABASE_NAME=${databaseName}",
            "DATABASE_HOST=${databaseHost}",
            "DATABASE_PORT=${databasePort}",
            "DATABASE_POOL=${databasePool}",
            "DATABASE_USERNAME=${databaseUser}",
            "DATABASE_PASSWORD=${databasePass}"
        ]) {
            sh '''
                apt-get update
                apt-get -y install postgresql-client libcurl3
                docker run --name postgres-pg-searchable -p${DATABASE_PORT}:5432 -e POSTGRES_PASSWORD=${DATABASE_PASSWORD} -d postgres:9.5
                gem install bundler --version=`sed -e '$!d' Gemfile.lock | xargs` --no-ri --no-rdoc
                gem install nexus --no-ri --no-rdoc
                bundle install --path vendor --without production --with test development
                bundle exec rake spec
            '''.stripIndent()
        }
        ruby.stepsRcovPublish()
    }

    stage('Run rubocop') {
        sh '''
            bundle exec rubocop
        '''
    }

    stage('Build gem') {
        sh '''
            bundle exec rake build
        '''
    }

    stage('Publish gem') {
        sh "gem nexus --url https://nexus.onsmartdev.media/repository/rubygems-hosted --credential ${nexusUser}:${nexusPass} pkg/*.gem"
    }
}
