pipeline {
  agent any

  options {
    timestamps()
    disableConcurrentBuilds()
  }

  parameters {
    booleanParam(name: 'RUN_TESTS', defaultValue: false, description: 'Run cargo tests')
    booleanParam(name: 'PUSH_IMAGES', defaultValue: true, description: 'Push images to registry')
    string(name: 'REGISTRY_CREDENTIALS_ID', defaultValue: 'registry-bstein-dev', description: 'Jenkins credentials id for registry.bstein.dev')
  }

  environment {
    REGISTRY = 'registry.bstein.dev'
    IMAGE_PREFIX = "${REGISTRY}/lesavka"
    CARGO_TERM_COLOR = 'always'
    DOCKER_BUILDKIT = '1'
  }

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

    stage('Format') {
      steps {
        sh 'cargo fmt --all --manifest-path common/Cargo.toml -- --check'
        sh 'cargo fmt --all --manifest-path server/Cargo.toml -- --check'
        sh 'cargo fmt --all --manifest-path client/Cargo.toml -- --check'
      }
    }

    stage('Clippy') {
      steps {
        sh 'cargo clippy --all-targets --manifest-path server/Cargo.toml -D warnings'
        sh 'cargo clippy --all-targets --manifest-path client/Cargo.toml -D warnings'
      }
    }

    stage('Build Dist') {
      steps {
        sh 'scripts/ci/build-dist.sh'
      }
    }

    stage('Tests') {
      when {
        expression { return params.RUN_TESTS }
      }
      steps {
        sh 'cargo test --manifest-path server/Cargo.toml'
        sh 'cargo test --manifest-path client/Cargo.toml'
      }
    }

    stage('Docker Login') {
      when {
        expression { return params.PUSH_IMAGES }
      }
      steps {
        withCredentials([
          usernamePassword(
            credentialsId: params.REGISTRY_CREDENTIALS_ID,
            usernameVariable: 'REGISTRY_USER',
            passwordVariable: 'REGISTRY_PASS'
          )
        ]) {
          sh 'echo "$REGISTRY_PASS" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin'
        }
      }
    }

    stage('Build Images') {
      steps {
        sh 'PUSH_IMAGES=${PUSH_IMAGES} scripts/ci/build-images.sh'
      }
    }
  }

  post {
    always {
      archiveArtifacts artifacts: 'dist/*.tar.gz', fingerprint: true, allowEmptyArchive: true
    }
  }
}
