// ERPNext → Coolify: validate, build custom image, push to Forgejo registry
pipeline {
  agent any

  environment {
    REGISTRY_IMAGE = 'git.aexoradao.com/epistemophiliac/erpnext'
    REGISTRY_HOST = 'git.aexoradao.com'
    FRAPPE_BRANCH = 'version-16'
  }

  options {
    timestamps()
    disableConcurrentBuilds()
    buildDiscarder(logRotator(numToKeepStr: '20'))
  }

  stages {
    stage('Verify') {
      steps {
        sh '''
          echo "=== ERPNext custom image CI ==="
          echo "commit: $(git rev-parse --short HEAD)"
          echo "branch: ${BRANCH_NAME:-main}"
          test -f Jenkinsfile
          test -f docker-compose.yml
          test -f example.env
          test -f apps.json
          test -f images/layered/Containerfile
        '''
      }
    }

    stage('Production readiness') {
      steps {
        sh '''
          chmod +x scripts/ci/*.sh
          bash scripts/ci/ci-readiness.sh .
          bash scripts/ci/validate-docker-compose.sh .
        '''
      }
    }

    stage('Bootstrap Docker tools') {
      steps {
        sh 'bash scripts/ci/jenkins-bootstrap.sh'
      }
    }

    stage('Compose validate') {
      steps {
        sh 'bash scripts/ci/jenkins-compose-validate.sh'
      }
    }

    stage('Build custom image') {
      steps {
        sh 'bash scripts/ci/jenkins-build-image.sh'
      }
    }

    stage('Push to Forgejo registry') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'forgejo-erpnext',
          usernameVariable: 'REGISTRY_USER',
          passwordVariable: 'REGISTRY_PASSWORD'
        )]) {
          sh 'bash scripts/ci/jenkins-push-image.sh'
        }
      }
    }

    stage('Verify registry pull') {
      steps {
        sh 'bash scripts/ci/jenkins-verify-image.sh'
      }
    }
  }

  post {
    success {
      archiveArtifacts artifacts: 'dist/*', fingerprint: true, onlyIfSuccessful: true
      echo '''
        CI passed.
        Image: git.aexoradao.com/epistemophiliac/erpnext:main-<sha> (+ :main)
        Coolify: set CUSTOM_IMAGE / CUSTOM_TAG from dist/coolify-image.env
      '''
    }
    failure {
      echo 'CI failed — image was not published.'
    }
  }
}
