#!/usr/bin/env groovy

// View Jenkins jobs at https://jenkins.nsi.rackspace.com/view/all/job/NSI-nscli/job/nscli/

//TODO: Unit Tests, Artifact Creation, Deployment

pipeline {
    options { disableConcurrentBuilds() }
    agent { label "IAD-DEV-BUILD-1" }
    stages {
        stage("Checkout Code") {
            steps {
                checkout scm
            }
        }
        stage("Build Base Testing Container") {
            // nscli_base doesn't contain any secrets
            steps {
                sh """docker build --add-host appstats.rackspace.com:127.0.0.1 \
                --add-host gatekeeper.nsi.rackspace.com:127.0.0.1 \
                --add-host sentry.nsi.rackspace.com:127.0.0.1 \
                --add-host facts-api.nsi.rackspace.com:10.2.247.156 \
                --format docker \
                --pull -t nscli_base:latest ."""
            }
        }
        stage("Install NSCLI in dev mode and Load Credentials") {
            steps {
                script {
                    // nscli_loaded is loaded with secrets and the current commit
                    withCredentials([file(credentialsId: 'credentials-json', variable: 'FILE')]) {
                        try {
                            sh "cp $FILE docker/credentials.json"
                            sh """echo 'FROM nscli_base:latest' | docker build --add-host \
                            facts-api.nsi.rackspace.com:10.2.247.156 \
                            --format docker -t nscli_loaded:latest . -f -"""
                        }
                        finally {
                            sh "rm -f docker/credentials.json"
                        }
                    }
                }
            }
        }
        stage("Lint") {
            steps {
                sh "docker run nscli_loaded:latest make lint"
            }
        }
//         stage("Tox") {
//             steps {
//                 script {
//                     try {
//                         sh "docker run nscli_loaded:latest bash -c '. ~/.bash_profile && make test --env JENKINS_TEST=true'"
//                     }
//                     // catching errors, but not failing builds yet
//                     catch (err) {
//                         echo err.getMessage()
//                     }
//                 }
//             }
//         }
    }
    post {
        cleanup {
            sh "docker container prune -f"
            sh "docker rmi nscli_loaded"
            sh "docker image prune -f"
        }
    }
}
