image: docker:24.0.6

include:
  - template: Security/Secret-Detection.gitlab-ci.yml

variables:
  GIT_DEPTH: 100

stages:
  - test
  - build
  - deploy

# 判断是不是正确的project，正确的branch，以及是不是forked repo过来的MR
.if-csghub-staging-original-repo: &if-csghub-staging-original-repo
  if: '$CI_COMMIT_REF_NAME == "csghub-staging" && $CI_PROJECT_ID == "171" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == null'

# for production docker image build
# e.g., v1.0.0
.if-production-tag-build: &if-production-tag-build
  if: '$CI_PROJECT_ID == "171" && $CI_COMMIT_TAG =~ /^v(\d+(?:\.\d+.\d+)*)$/'

csghub-build:
  stage: build
  services:
    - docker:24.0.6-dind
  tags:
    - external
  rules:
    - <<: *if-csghub-staging-original-repo
  variables:
    IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG
    DOCKER_HOST: "tcp://docker:2375"
    DOCKER_TLS_CERTDIR: ""
    BUILDX_NO_DEFAULT_ATTESTATIONS: 1
  before_script:
    - apk add --no-cache --virtual .build-deps curl
    - mkdir -p ~/.docker/cli-plugins
    - curl -SL https://github.com/docker/buildx/releases/download/v0.17.1/buildx-v0.17.1.linux-amd64 -o ~/.docker/cli-plugins/docker-buildx
    - chmod +x ~/.docker/cli-plugins/docker-buildx
    - docker login $CI_REGISTRY -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN
  script:
    - docker buildx build --platform linux/amd64,linux/arm64 -t ${IMAGE_TAG} --push .

csghub-deploy:
  stage: deploy
  tags:
    - external
  rules:
    - <<: *if-csghub-staging-original-repo
  variables:
    IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
  before_script:
    - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - echo "$OPEN_PORTAL_STAGING_PEM" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $OPEN_PORTAL_STAGING_HOST >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts
  script:
    - |
        ssh root@$OPEN_PORTAL_STAGING_HOST "/bin/bash -s" << EOT
          export DEPLOY_IMAGE_TAG=$IMAGE_TAG
          cd /root/open_portal/
          docker compose -f docker_compose_staging.yml pull go-web
          docker compose -f docker_compose_staging.yml up -d --force-recreate go-web
          docker image prune -f
        EOT