@Library('jenkins-common') _

utils.initProperties()

def appName       = 'vendor-scheduler'

def databaseName  = 'vendor-scheduler'
def databaseHost  = 'localhost'
def databasePort  = '5432'
def databasePool  = '10'
def databaseUser  = 'postgres'
def databasePass  = 'vaequ7Luah2gup7aaz3U'

testEnv = [
    "DATABASE_NAME=${databaseName}",
    "DATABASE_HOST=${databaseHost}",
    "DATABASE_PORT=${databasePort}",
    "DATABASE_POOL=${databasePool}",
    "DATABASE_USERNAME=${databaseUser}",
    "DATABASE_PASSWORD=${databasePass}",

    "APP_NAME=${appName}",
    "LOG_LEVEL=debug",
    "RAILS_MAX_THREADS=5",
    "PORT=5090",
    "SECRET_KEY_BASE=abc123",
    "TMPDIR=/tmp"
]

utils.onNode(nodeLabel: 'ubuntu-ruby-255') {
    String version = utils.stagesGitCheckout()

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

    stage('Run tests') {
        withEnv(testEnv) {
            sh '''
                apt-get update
                apt-get -y install postgresql-client libcurl3
                gem install bundler --version=`sed -e '$!d' Gemfile.lock | xargs` --no-ri --no-rdoc
                bundle install --path vendor --without production --with test development
                docker run --rm --name postgres-${APP_NAME} -p${DATABASE_PORT}:5432 -e POSTGRES_PASSWORD=${DATABASE_PASSWORD} -d postgres:11
                bundle exec rake db:create db:schema:load db:migrate RAILS_ENV=test
                bundle exec rspec
                docker stop postgres-${APP_NAME}
            '''.stripIndent()
        }
        ruby.publishCoberturaReports()
    }

    //ruby.stagesRunCheckstyle() // TODO: reenable when we move to Ruby 2.2/later

    stage('Create artifact for S3') {
        withEnv([
            "appName=${appName}",
            "version=${version}"
        ]) {
            sh '''
                mkdir ${appName}-synced
                rsync -av --exclude 'vendor' --exclude ${appName}-synced --exclude '.git' --include '*/' --include '*'  . ${appName}-synced/
                mv ${appName}-synced ${appName}
                zip -r ${appName}-${version}.zip ${appName} -x '.git/*'
            '''.stripIndent()
        }
    }

    withAWS(credentials:'aws-s3') {
        utils.stagesUploadArtifactToS3(includePathPattern:"${appName}*.zip", "${appName}", 'vle')
    }
}
