name: Build scheduler-backend image

on:
  push:
    branches: [dev, main]
    paths:
      - "**"
  workflow_dispatch:
    inputs:
      tag:
        description: "Optional image tag. Defaults to <branch>-<short-sha>."
        required: false
        default: ""

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

env:
  REGISTRY: docker.io
  DOCKER_USER: ${{ secrets.DOCKER_USERNAME || 'mag1666888' }}
  SERVICE_NAME: scheduler-backend
  DEPLOYMENT_NAME: scheduler-backend
  CONFIG_CENTER_CONTAINER: scheduler-backend
  DOCKERFILE: Dockerfile
  INPUT_TAG: ${{ github.event.inputs.tag }}

jobs:
  build-and-push:
    runs-on: [openim, config-center]
    steps:
      - name: Configure SSH
        env:
          GIT_SSH_PRIVATE_KEY: ${{ secrets.GIT_SSH_PRIVATE_KEY }}
        run: |
          set -euo pipefail

          if [ -z "${GIT_SSH_PRIVATE_KEY:-}" ]; then
            echo "GIT_SSH_PRIVATE_KEY is required."
            exit 1
          fi

          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          if printf '%s' "$GIT_SSH_PRIVATE_KEY" | grep -q "BEGIN .*PRIVATE KEY"; then
            printf '%s\n' "$GIT_SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
          else
            printf '%s' "$GIT_SSH_PRIVATE_KEY" | base64 -d > ~/.ssh/id_rsa
          fi
          chmod 600 ~/.ssh/id_rsa
          ssh-keyscan -H git.imall.cloud >> ~/.ssh/known_hosts 2>/dev/null || true
          chmod 644 ~/.ssh/known_hosts
          ssh -o BatchMode=yes -o StrictHostKeyChecking=yes -T git@git.imall.cloud || true

      - name: Checkout
        run: |
          set -euo pipefail

          BRANCH_NAME="${GITHUB_REF_NAME:-${GITEA_REF_NAME:-main}}"
          COMMIT_SHA="${GITHUB_SHA:-${GITEA_SHA:-}}"

          git init .
          git remote remove origin 2>/dev/null || true
          git remote add origin git@git.imall.cloud:im-group/scheduler-backend.git
          if [ -n "$COMMIT_SHA" ]; then
            git fetch --depth 1 origin "$COMMIT_SHA"
          fi
          if [ -z "$COMMIT_SHA" ]; then
            git fetch --depth 1 origin "$BRANCH_NAME"
          fi
          git checkout --force FETCH_HEAD

      - name: Login to Docker Hub
        uses: docker/login-action@v3.3.0
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3.8.0

      - name: Test
        run: |
          set -euo pipefail

          docker build \
            --target test \
            -f "$DOCKERFILE" \
            .

      - name: Build and push image
        run: |
          set -euo pipefail

          SHORT_SHA="$(git rev-parse --short=7 HEAD)"
          BRANCH_NAME="${GITHUB_REF_NAME:-${GITEA_REF_NAME:-$(git rev-parse --abbrev-ref HEAD)}}"
          BRANCH_TAG="$(printf '%s' "$BRANCH_NAME" | sed 's/[^a-zA-Z0-9-]/-/g' | tr '[:upper:]' '[:lower:]')"
          if [ -n "${INPUT_TAG:-}" ]; then
            VERSION_TAG="$INPUT_TAG"
          else
            VERSION_TAG="${BRANCH_TAG}-${SHORT_SHA}"
          fi

          IMAGE="${DOCKER_USER}/${SERVICE_NAME}:${VERSION_TAG}"
          docker buildx build \
            --platform linux/amd64 \
            -f "$DOCKERFILE" \
            -t "$IMAGE" \
            --push \
            .

          echo "Built and pushed $IMAGE for deployment $DEPLOYMENT_NAME"

          CONFIG_CENTER_UPDATES_FILE="$(mktemp)"
          export CONFIG_CENTER_UPDATES_FILE
          printf '%s|%s|%s\n' "$DEPLOYMENT_NAME" "$IMAGE" "$CONFIG_CENTER_CONTAINER" > "$CONFIG_CENTER_UPDATES_FILE"

          if [ "$BRANCH_NAME" = "dev" ]; then
            CONFIG_CENTER_CLUSTERS="${CONFIG_CENTER_CLUSTERS:-ack-dev}" \
              bash .gitea/scripts/update-config-center-images.sh
          elif [ "$BRANCH_NAME" = "main" ]; then
            CONFIG_CENTER_CLUSTERS="${CONFIG_CENTER_CLUSTERS:-ack-fumin ack-yuanmeng ack-zhongyi ack-renmin}" \
              bash .gitea/scripts/update-config-center-images.sh
          else
            echo "Branch is $BRANCH_NAME; config-center auto update is only enabled for dev and main."
          fi
