stages:
  - build
  - deploy

default:
  tags:
    - devops-runner
  image: docker:latest
  services:
    - docker:dind

variables:
  HARBOR_SERVICE: "harbor.linkfog.cn"
  HARBOR_REGISTRY: "sub2api"
  HARBOR_USERNAME: "public"
  HARBOR_PASSWORD: "LinkfogHarbor2024@"
  VERSION: ""
  COMMIT: ""
  DATE: ""

workflow:
  rules:
    - if: $CI_COMMIT_TAG
      when: always

.docker-build-push-template: &docker-build-push-template
  script:
    - set -eo pipefail
    - echo "DEBUG----- $(date '+%Y-%m-%d %H:%M:%S') Starting build process"
    - |
      if [ -n "$CI_COMMIT_TAG" ]; then
        echo "IMAGE_TAG=${CI_COMMIT_TAG#sub2api/}"
      else
        echo "IMAGE_TAG=$CI_COMMIT_REF_NAME"
      fi
    - echo "Logging into Harbor..."
    - echo "$HARBOR_PASSWORD" | docker login -u "$HARBOR_USERNAME" --password-stdin "$HARBOR_SERVICE"
    - docker build -f Dockerfile --build-arg VERSION="${VERSION}" --build-arg COMMIT="${COMMIT}" --build-arg DATE="${DATE}" -t "$HARBOR_SERVICE/$HARBOR_REGISTRY/sub2api:${IMAGE_TAG}" .
    - docker push "$HARBOR_SERVICE/$HARBOR_REGISTRY/sub2api:${IMAGE_TAG}"
    - docker rmi "$HARBOR_SERVICE/$HARBOR_REGISTRY/sub2api:${IMAGE_TAG}" || true

sub2api:
  stage: build
  <<: *docker-build-push-template
  variables:
    VERSION: "${CI_COMMIT_TAG:-}"
    COMMIT: "${CI_COMMIT_SHA}"
    DATE: "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  rules:
    - if: $CI_COMMIT_TAG =~ /^sub2api\/v/
      when: always
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: always
