image:
  name: savonet/liquidsoap:v2.1.0
  entrypoint: [""]

stages:
  - test
  - release

.install_requirements: &install_requirements
  - whoami
  - apt-get -qq update
  - apt-get -y install codespell make

.release-rules: &release-rules
  # rule to run job on a tag-reference which has the form number.number.number (semantic versioning)
  # or number.number.number-text (semantic versioning + release-name)
  # and where a Dockerfile exists
  - if: $CI_COMMIT_TAG =~ /^\d+[.]\d+[.]\d+$/ || $CI_COMMIT_TAG =~ /^\d+[.]\d+[.]\d+[-]\S+$/
    exists:
      - Dockerfile

check_spelling:
  image: python:3.9
  stage: test
  before_script:
    - *install_requirements
  script:
    make spell

check_code:
  stage: test
  script:
    liquidsoap --check src/engine.liq

run_tests:
  stage: test
  script:
    - cd tests
    - liquidsoap engine_test_suite.liq

docker-push:
  # Use the official docker image.
  image: docker:latest
  stage: release
  variables:
    # the name of the image without version
    AURA_IMAGE_NAME: "autoradio/engine-core"
  services:
    - docker:dind
  script:
    # every commit on main branch should build and push image as unstable
    # elseif its a protected branch and push to gitlab registry
    # else it is from a tag (enforced by gitlab-ci rules)
    # hint: tags are references independent of branches
    # hint: feature branches must begin with "feat"
    - |
      if [ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]
        then docker login -u "$DOCKER_ID" -p "$DOCKER_HUB_AUTH"
        docker build -t $AURA_IMAGE_NAME:main -t $AURA_IMAGE_NAME:main-$CI_COMMIT_SHORT_SHA .
        docker push --all-tags $AURA_IMAGE_NAME
      elif [ "$CI_COMMIT_REF_PROTECTED" = "true" ] && [ "$CI_COMMIT_BRANCH" != "$CI_DEFAULT_BRANCH" ]
        then docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
        docker build -t $AURA_IMAGE_NAME -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
        docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
      else
        docker login -u "$DOCKER_ID" -p "$DOCKER_HUB_AUTH"
        docker build -t $AURA_IMAGE_NAME -t $AURA_IMAGE_NAME:$CI_COMMIT_TAG .
        docker push $AURA_IMAGE_NAME:$CI_COMMIT_TAG
      fi
  rules:
    - *release-rules
    # every commit on master/main or feature branch should trigger a push
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH || $CI_COMMIT_REF_PROTECTED =~ "true"
      exists:
        - Dockerfile

release_job:
  stage: release
  needs:
    - docker-push
  image: registry.gitlab.com/gitlab-org/release-cli:latest
  rules: *release-rules
  script:
    - echo "this will be a release when there is a tag, but tags should be protected to be only createable by maintainers."
  release:
    name: 'Release $CI_COMMIT_TAG'
    description: ./CHANGELOG.md
    tag_name: '$CI_COMMIT_TAG'
    ref: '$CI_COMMIT_TAG'
