import static groovy.json.JsonOutput.*

def runMoleculeTests = true

properties([pipelineTriggers([githubPush()])])
pipeline {
    agent { label 'csdac-prod' }

  environment {
    DATESTAMP = "${Calendar.getInstance()format('yyyyMMddHHmmss')}"
    ARTIFACT_NAME = 'cisco-csdac'
    ARTIFACTORY_FQDN = 'engci-maven-master.cisco.com'
  }

  options {
    buildDiscarder(logRotator(daysToKeepStr: '90', artifactDaysToKeepStr: '0'))
    disableConcurrentBuilds()
    timestamps()
    ansiColor('xterm')
  }

  parameters {
    booleanParam(name: 'UPLOAD_TO_ARTIFACTORY', defaultValue: false, description: 'Upload package to Artifactory')
    booleanParam(name: 'UPLOAD_TO_GALAXY', defaultValue: false, description: 'Upload package to ansible galaxy')
    booleanParam(name: 'RUN_MOLECULE_TEST', defaultValue: false, description: 'Running molecule test to verify the role')
    string(name: 'GALAXY_PACKAGE_VERSION', defaultValue: '', description: 'Version for ansible package')
  }

    stages {

    stage('Init') {
      steps {
        script {
          def causes = currentBuild.getBuildCauses()
          //echo prettyPrint(toJson(causes))
          if ( (currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause') == true) && (env.CHANGE_ID == null) ) {
            runMoleculeTests = false
          }
          else if ( (currentBuild.getBuildCauses('hudson.model.Cause$UpstreamCause')) && (env.CHANGE_ID == null) ) {
            runMoleculeTests = false
          }
        }
      }
    }
    stage('Prepare private key file') {
      steps {
        withCredentials([file(credentialsId: 'muster-vm-key', variable: 'MUSTER_VM_KEY')]) {
          sh 'chmod 0400 ${MUSTER_VM_KEY}; mv ${MUSTER_VM_KEY} ~/muster_vm_id_rsa'
        }
      }
    }
    stage('Prepare valut file') {
      steps {
        withCredentials([file(credentialsId: 'muster-vm-vault', variable: 'MUSTER_VM_VAULT')]) {
          sh 'mv ${MUSTER_VM_VAULT} ~/vault.pw'
        }
      }
    }

stage('Define SKIP_VERIFICATION environment') {
 steps {
   script {
     env.SKIP_VERIFICATION = '0'
     if (env.BRANCH_NAME == 'master') {
        env.SKIP_VERIFICATION = '1'
      }
   }
 }
}
stage('Prepare templates and versions') {
  steps {
   sh '''
       for i in `find ./muster-docker -name "*.j2"  -print`; do
  if [ ! -d $i ];
    then filePath=`basename $i`;
    echo $filePath
         cp $i ./roles/csdac/templates/$filePath;
  fi;
done
   '''
  sh 'cp ./muster-docker/onprem/muster-cli ./roles/csdac/files/muster-cli'
  sh """
     cat ./muster-docker/prod.json | yq -P >> ./roles/csdac/vars/main.yml
     echo "MUSTER_SKIP_VERIFICATION: ${SKIP_VERIFICATION}" >> ./roles/csdac/vars/main.yml
     cat "./roles/csdac/vars/main.yml"
     """
  }
}

     stage('Run test') {
     when { expression {  params.RUN_MOLECULE_TEST == true } }
       steps {
         sh 'molecule test --destroy=never'
       }
     }

     stage('Upload artificats to dockerhub') {
     when { expression { params.UPLOAD_TO_ARTIFACTORY == true } }
     steps {
      script {
      // Update ansible galaxy version
      update_version = sh(returnStdout: true, script: 'sed -i.bak "/^[[:space:]]*version:/ s/:.*/: ${GALAXY_PACKAGE_VERSION}/" galaxy.yml')
      // Create tar gunzip file
      sh '''
          ansible-galaxy collection build --force
      '''
      withCredentials([usernamePassword(credentialsId: 'cisco-dockerhub-id', usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
      sh 'curl  --user $USERNAME:$PASSWORD --upload-file ${WORKSPACE}/cisco-csdac*  -X PUT  "https://${ARTIFACTORY_FQDN}/artifactory/csdac-cdn/ansible/${ARTIFACT_NAME}-${GALAXY_PACKAGE_VERSION}.tar.gz" --insecure'
     }
     }
     }


}
     stage('Upload artificats to ansible galaxy') {
     when { expression { params.UPLOAD_TO_GALAXY == true } }
     steps {
      script {
     // Upload the ansible galaxt using galaxy importer
      sh 'python3 -m galaxy_importer.main ${ARTIFACT_NAME}-${GALAXY_PACKAGE_VERSION}.tar.gz'
     }
     }


}
    }
  post {
    cleanup { cleanWs() }
  }
}
