pipeline {
  agent any

  environment {
    REGISTRY = "docker.internal.jason-e.dev:8443"
    IMAGE_NAME = "efstajas/homepage"
  }

  stages {
    stage('Docker Build') {
      steps {
        script {
          dockerImage = docker.build("$IMAGE_NAME")
        }
      }
    }

    stage('Docker Publish') {
      steps {
        script {
          docker.withRegistry("https://$REGISTRY") {
            dockerImage.push("latest")
          }
        }
      }
    }

    stage('Deploy to Nomad') {
      steps {
        script {
           // Calculate the hash of your Docker image (or your application code)
          def imageHash = sh(script: "docker images --no-trunc $IMAGE_NAME | grep latest | awk '{print \$3}'", returnStdout: true).trim()

          // Read the jobspec.json file
          def jobSpec = readJSON file: 'jobspec.json'

          sh 'curl -X POST -H "Content-Type: application/json" -d "$jobSpec" http://nomad.service.consul:4646/v1/jobs'
        }
      }
    }
  }
}
