@Library('nf-jenkins-shared-libraries')_  

def repo = "nf-mop-tf"

pipeline {
    agent {
        dockerfile { 
            filename 'Dockerfile.build'
            args '-u 0 --privileged'
        }
    }
    environment {
        BITBUCKET_AUTH = credentials('bitbucket_auth')
    }
    stages {
        stage("Build"){
            steps {
                echo "Building nf-mop-tf"
            }
        }
        stage('Terraform'){
            steps {
                script {
                    dir("mop"){
                        run_terraform directory: "sre", environment: "sandbox"
                    }
                }
            }
        }
    }
    post {
        always {
            bitbucketStatus repo: "${repo}", BRANCH_NAME: BRANCH_NAME, GIT_COMMIT: GIT_COMMIT, status: "SUCCESSFUL"
        }
    }
}

def run_terraform( params ) {
  def directory = params.directory ?: "terraform"
  def environment = params.environment 
  def commit_hash = params.commit_hash ?: "sandbox"

  def workspace = (environment == "sandbox") ? "nf-sandbox": "nf-${environment}-int"

  if( environment == "production"){
    workspace = "nf-prod-int"
  }
  def command = ""
  def command_plan = ""
  command_plan = "terraform init;"+
                 "terraform workspace select ${workspace}; " +
                 "terraform init;"+
                 "terraform workspace list;"
  
  dir("${directory}") {
    withCredentials([[$class: 'AmazonWebServicesCredentialsBinding', credentialsId: "	aws_trial_opsmgt", variable: 'AWS_ACCESS_KEY_ID']]) {
      sh "ls -ltr"
      sh "rm -rf .terraform"
      sh "${command_plan}"
      sh "${command}"
  }
  }
}