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
        export IMAGE_TAG="${CI_COMMIT_TAG#sub2api/}"
      else
        export IMAGE_TAG="$CI_COMMIT_REF_NAME"
      fi
      echo "Image tag: $IMAGE_TAG"
    - 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}" -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}"
  rules:
    - if: $CI_COMMIT_TAG =~ /^sub2api\/v/
      when: always
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: always
