variables:
  DOCKER_HOST: $DOCKER_HOST_BIO
  PROJECT_NAME: "backend"

cache:
  key: $CI_COMMIT_REF_NAME
  paths:
    - build/

stages:
  - build
  - verification
  - publish
  - cleanup



# ===========================================================================
# Stage: build
# ===========================================================================

gradlew-bootJar:
  stage: build
  tags:
    - worker
  image: eclipse-temurin:11-jdk-alpine
  script:
    - ./gradlew bootJar


docker-build-latest:
  stage: build
  image: docker:git
  tags:
    - cache
  only:
    refs:
      - main
  except:
    variables:
      - $CI_COMMIT_TAG
  before_script:
    - mkdir -p build
  script:
    - docker build -t $DOCKER_NAMESPACE/$PROJECT_NAME:latest .
    - docker save -o build/image.tar $DOCKER_NAMESPACE/$PROJECT_NAME:latest


docker-build-tag:
  stage: build
  image: docker:git
  tags:
    - cache
  only:
    variables:
      - $CI_COMMIT_TAG
  before_script:
    - mkdir -p build
  script:
    - docker build -t $DOCKER_NAMESPACE/$PROJECT_NAME:$CI_COMMIT_TAG .
    - docker save -o build/image.tar $DOCKER_NAMESPACE/$PROJECT_NAME:$CI_COMMIT_TAG 



# ===========================================================================
# Stage: test
# ===========================================================================

verification-unit:
  stage: verification
  image: eclipse-temurin:11-jdk-alpine
  tags:
    - worker
  allow_failure: true
  script:
    - ./gradlew test
  artifacts:
    when: always
    reports:
      junit: build/test-results/test/**/TEST-*.xml
    expire_in: 10 mins


# ===========================================================================
# Stage: publish
# ===========================================================================

docker-push-latest:
  stage: publish
  image: docker
  tags:
    - cache
  only:
    - main
  before_script:
    - docker login -u $DOCKER_USERNAME -p $DOCKER_TOKEN $DOCKER_REGISTRY
  script:
    - docker load -i build/image.tar
    - docker push $DOCKER_NAMESPACE/$PROJECT_NAME:latest

docker-push-tag:
  stage: publish
  image: docker
  tags:
    - cache
  only:
    variables:
      - $CI_COMMIT_TAG
  before_script:
    - docker login -u $DOCKER_USERNAME -p $DOCKER_TOKEN $DOCKER_REGISTRY
  script:
    - docker load -i build/image.tar
    - docker push $DOCKER_NAMESPACE/$PROJECT_NAME:$CI_COMMIT_TAG

cleanup:
  stage: cleanup
  image: docker:git
  tags:
    - cache
  script:
    - docker image prune || true
    - rm -rf build/ || true
  when: always
  allow_failure: true
