stages:
  - build
  - post-deploy

variables:
  GIT_DEPTH: 1
  SHA_IMAGE_TAG: $CI_REGISTRY/salesrabbit/services/<APP_NAME>:$CI_COMMIT_SHORT_SHA

image: hexpm/elixir:1.14.2-erlang-25.0.2-debian-bullseye-20210902-slim

test:
  stage: build
  coverage: /\[TOTAL\]\s+(\d+\.\d+)%/
  variables:
    LOG_LEVEL: warn
    MIX_ENV: test
    COVER_DIR: $CI_PROJECT_DIR
  cache:
    key: ${CI_JOB_NAME}
    paths:
      - deps
      - _build/test/lib
  before_script:
    - mix local.rebar --force
    - mix local.hex --force
    - mix deps.get
  script:
    - mix run_ci
  artifacts:
    when: always
    paths:
      - test_report.xml
    reports:
      junit: test_report.xml
  tags:
    - development

build:
  stage: build
  image: docker
  services:
    - docker:dind
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker build -t $SHA_IMAGE_TAG --build-arg CI_COMMIT_SHORT_SHA .
    - docker push $SHA_IMAGE_TAG
  tags:
    - development

build_client:
  stage: build
  variables:
    MIX_ENV: prod
  cache:
    key: ${CI_JOB_NAME}
    paths:
      - sdk
  before_script:
    - mix local.rebar --force
    - mix local.hex --force
    - mix deps.get
  script:
    - mix build_sdk
  artifacts:
    when: always
    paths:
      - sdk

tag_latest:
  stage: post-deploy
  image: docker
  services:
    - docker:dind
  dependencies:
    - build
  variables:
    MASTER_IMAGE_TAG: $CI_REGISTRY/salesrabbit/services/<APP_NAME>:latest
  before_script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
  script:
    - docker pull $SHA_IMAGE_TAG
    - docker tag $SHA_IMAGE_TAG $MASTER_IMAGE_TAG
    - docker push $MASTER_IMAGE_TAG
  only:
    - main
  tags:
    - development

pages:
  stage: post-deploy
  dependencies: 
    - test
  variables:
    MIX_ENV: test
  before_script:
    - mix local.rebar --force
    - mix local.hex --force
    - mix deps.get
  script:
    - mix docs
    - mv doc public
  artifacts:
    paths:
      - public
  rules:
    - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
