stages:
  - test
  - release
  - build

test docker:
  stage: test
  image: griefed/gitlab-ci-cd:1.0.0
  services:
    - name: docker:dind
      alias: docker
  variables:
    project_name: $CI_PROJECT_NAME
    SEMANTIC_RELEASE_PACKAGE: $CI_PROJECT_NAME
  before_script:
    - docker login -u "$DOCKERHUB_USER" -p "$DOCKERHUB_TOKEN" docker.io
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker login -u "$DOCKERHUB_USER" -p "$GITHUB_TOKEN" ghcr.io
    - docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
    - docker buildx create --use --name grfdbuilder
  script:
    - docker buildx build
      --push
      --platform linux/amd64,linux/arm/v7,linux/arm64
      --tag "index.docker.io/$DOCKERHUB_USER/$DOCKERHUB_REPO:develop"
      --tag "$CI_REGISTRY_IMAGE:develop"
      --tag "ghcr.io/$DOCKERHUB_USER/$DOCKERHUB_REPO:develop" .
  except:
    refs:
      - tags
    variables:
      - $CI_COMMIT_TITLE =~ /^RELEASE:.+$/

release:
  needs: ['test docker']
  stage: release
  image: griefed/gitlab-ci-cd:1.0.0
  services:
    - name: docker:dind
      alias: docker
  variables:
    project_name: $CI_PROJECT_NAME
    SEMANTIC_RELEASE_PACKAGE: $CI_PROJECT_NAME
  script:
    - npx semantic-release
  only:
    - main
  except:
    refs:
      - tags
    variables:
      - $CI_COMMIT_TITLE =~ /^RELEASE:.+$/

build:
  stage: build
  image: griefed/gitlab-ci-cd:1.0.0
  services:
    - name: docker:dind
      alias: docker
  variables:
    project_name: $CI_PROJECT_NAME
    SEMANTIC_RELEASE_PACKAGE: $CI_PROJECT_NAME
  before_script:
    - docker login -u "$DOCKERHUB_USER" -p "$DOCKERHUB_TOKEN" docker.io
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker login -u "$DOCKERHUB_USER" -p "$GITHUB_TOKEN" ghcr.io
    - docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
    - docker buildx create --use --name grfdbuilder
  script:
    - docker pull "$CI_REGISTRY_IMAGE:develop"
    - docker buildx build
      --push
      --platform linux/amd64,linux/arm/v7,linux/arm64
      --cache-from "$CI_REGISTRY_IMAGE:develop"
      --tag "$CI_REGISTRY_IMAGE:latest"
      --tag "ghcr.io/$DOCKERHUB_USER/$DOCKERHUB_REPO:$CI_COMMIT_TAG"
      --tag "ghcr.io/$DOCKERHUB_USER/$DOCKERHUB_REPO:latest"
      --tag "index.docker.io/$DOCKERHUB_USER/$DOCKERHUB_REPO:$CI_COMMIT_TAG"
      --tag "index.docker.io/$DOCKERHUB_USER/$DOCKERHUB_REPO:latest" .
  only:
    - tags
