pipeline {
  agent any

  environment {
    REGISTRY       = 'registry.dwarrington.com'
    IMAGE_NAME     = 'cabrits'
    IMAGE_TAG      = "${env.BUILD_NUMBER}"
    CREDENTIALS_ID = 'registry-creds'
    SUBDIR         = ''
    COMPOSE_FILE   = 'docker-compose.yml'
    SERVICE_NAME   = 'cabrits'
  }

  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }

    stage('Build & Push') {
      steps {
        script {
          docker.withRegistry("https://${REGISTRY}", CREDENTIALS_ID) {
            def buildArgs = (!env.SUBDIR || env.SUBDIR.trim() == '')
              ? "-f Dockerfile ."
              : "-f ${env.SUBDIR}/Dockerfile ${env.SUBDIR}"

            def img = docker.build("${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}", buildArgs)
            img.push()
            img.push('latest')
          }
        }
      }
    }

    stage('Deploy') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: CREDENTIALS_ID,
          usernameVariable: 'DOCKER_USER',
          passwordVariable: 'DOCKER_PASS'
        )]) {
          sh '''
            export PATH=$PATH:/usr/libexec/docker/cli-plugins:/usr/bin:/usr/local/bin

            echo "$DOCKER_PASS" | docker login ${REGISTRY} -u "$DOCKER_USER" --password-stdin

            sed -i "/${SERVICE_NAME}:/,/image:/s|image:.*|image: ${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}|" ${COMPOSE_FILE}

            docker compose -f ${COMPOSE_FILE} pull ${SERVICE_NAME}
            docker compose -f ${COMPOSE_FILE} up -d --force-recreate --remove-orphans
          '''
        }
      }
    }
  }
}
