---
services:
  - postgres:latest

variables:
  POSTGRES_HOST: postgres
  POSTGRES_HOST_AUTH_METHOD: trust
  MIX_ENV: "test"

stages:
  - test
  - publish
  - deploy

.elixir: &elixir
  image: elixir:1.16
  before_script:
    - curl https://sh.rustup.rs -sSf | sh -s -- -y
    - source $HOME/.cargo/env
    - rustc --version
    - cargo --version
    - mix local.hex --force
    - mix local.rebar --force
    - mix deps.get --only $MIX_ENV

lint:xmplry:
  extends: .elixir
  stage: test
  variables:
    MIX_ENV: test
  script:
    - mix compile --warnings-as-errors --force
    - mix format --check-formatted
    - mix sobelow --config
    - mix deps.audit

test:xmplry:
  extends: .elixir
  stage: test
  variables:
    MIX_ENV: test
  script:
    - mix ecto.create
    - mix ecto.migrate
    - mix test --cover
  coverage: /\d+.\d+\%\s+\|\s+Total/
  artifacts:
    when: always
    paths:
      - _build/test/lib/xmplry/test-junit-report.xml
    reports:
      junit: _build/test/lib/xmplry/test-junit-report.xml

package:xmplry:
  stage: publish
  extends:
    - .elixir
  variables:
    MIX_ENV: prod
    ARCH: amd64
  script:
    - mix assets.deploy
    - mix release --overwrite
    - ARTIFACT_NAME="$(find . -name "xmplry-*.tar.gz" -exec basename {} .tar.gz \;)"
    - mv _build/prod/${ARTIFACT_NAME}.tar.gz ${ARTIFACT_NAME}-${ARCH}.tar.gz
  artifacts:
    name: "xmplry-${CI_COMMIT_REF_SLUG:-CI_COMMIT_SHA}-${ARCH}.tar.gz"
    paths:
      - xmplry-*.tar.gz
  rules:
    - if: $CI_COMMIT_TAG
    - if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"

image:xmplry:
  stage: publish
  image:
    name: gcr.io/kaniko-project/executor:debug
    entrypoint: [""]
  script:
    - mkdir -p /kaniko/.docker
    - echo "{\"auths\":{\"${CI_REGISTRY}\":{\"auth\":\"$(printf "%s:%s" "${CI_REGISTRY_USER}" "${CI_REGISTRY_PASSWORD}" | base64 | tr -d '\n')\"}}}" > /kaniko/.docker/config.json
    - >-
      /kaniko/executor
      --context "${CI_PROJECT_DIR}"
      --dockerfile "${CI_PROJECT_DIR}/Dockerfile"
      --destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_TAG}"
  rules:
    - if: $CI_COMMIT_TAG

release:xmplry:
  stage: publish
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  rules:
    - if: $CI_COMMIT_TAG
  script:
    - echo "running release_job"
  release:
    tag_name: "$CI_COMMIT_TAG"
    description: "$CI_COMMIT_TAG"

deploy:xmplry:
  stage: deploy
  image: golang:1.13
  rules:
    - if: $CI_COMMIT_TAG
  before_script:
    - apt-get update -qq && apt-get install -y curl
    - curl -L https://fly.io/install.sh | sh
  script:
    - /root/.fly/bin/flyctl deploy --remote-only