stages:
  - test
  - deploy_tags
  - deploy

cache:
  paths:
    - _build/
    - deps/

variables:
  POSTGRES_PASSWORD: "postgres"
  POSTGRES_USER: "postgres"
  DATABASE_URL: "postgres"
  MIX_ENV: "test"
  DOCKER_TLS_CERTDIR: "/certs"
  DOCKER_HOST: tcp://docker:2376

test:
  stage: test
  needs: []
  image: "elixir:1.10"
  services:
  - name: postgres:12
  script: script/cibuild

build_image_for_commit:
  stage: test
  needs: []
  image: "docker:19.03.12"
  only:
    - master
  services:
    - name: docker:19.03.12-dind
  script:
    - docker login "https://${CI_REGISTRY}" -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    - docker pull $CI_REGISTRY_IMAGE:latest || true
    - docker build --cache-from $CI_REGISTRY_IMAGE:latest -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA

deploy_to_tags:
  stage: deploy_tags
  needs: ['test']
  image: "node:15.0"
  only:
    - master
  script:
    - npm install
    - npx semantic-release --repository-url=$CI_REPOSITORY_URL
    - script/generate-build-version
  artifacts:
    reports:
      dotenv: build.env

deploy_commit_image_to_tag:
  stage: deploy
  needs:
    - build_image_for_commit
    - job: deploy_to_tags
      artifacts: true
  only:
    - master
  image: "docker:19.03.12"
  services:
    - name: docker:19.03.12-dind
  script:
    - echo "BUILD_VERSION is ${BUILD_VERSION}"
    - docker login "https://${CI_REGISTRY}" -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD
    # Run the docker pull, but retry if it doesn't work at first because layers may be
    # still be loading to storage
    - for i in 1 2 3 4 5; do docker pull $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA && break || sleep 15; done
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:$BUILD_VERSION
    - docker tag $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA $CI_REGISTRY_IMAGE:latest
    - docker push $CI_REGISTRY_IMAGE:$BUILD_VERSION
    - docker push $CI_REGISTRY_IMAGE:latest
