name: Build Baron SSO RC

on:
  workflow_dispatch:
    inputs:
      version_tag:
        description: "The version tag to release to staging (e.g., v1.2601.1)"
        required: true
        type: string

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install dependencies
        run: sudo apt-get update && sudo apt-get install -y jq curl

      - name: Login to Docker Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ vars.HARBOR_ENDPOINT }}
          username: ${{ vars.HARBOR_ROBOT_ACCOUNT }}
          password: ${{ secrets.HARBOR_ROBOT_KEY }}

      - name: Calculate next RC tag
        id: rc_calculator
        env:
          INPUT_TAG: ${{ github.event.inputs.version_tag }}
          REGISTRY_URL: ${{ vars.HARBOR_ENDPOINT }}
          HARBOR_USER: ${{ vars.HARBOR_ROBOT_ACCOUNT }}
          HARBOR_PASSWORD: ${{ secrets.HARBOR_ROBOT_KEY }}
        run: |
          # Generate YYMM dynamically for the new tag
          CURRENT_YYMM=$(date +'%y%m')

          # Reconstruct the base tag with the current YYMM
          MAJOR_VERSION=$(echo "${INPUT_TAG}" | cut -d'.' -f1)
          MINOR_VERSION=$(echo "${INPUT_TAG}" | cut -d'.' -f3)
          BASE_TAG="${MAJOR_VERSION}.${CURRENT_YYMM}.${MINOR_VERSION}"

          echo "Input tag: ${INPUT_TAG}"
          echo "Generated dynamic base tag: ${BASE_TAG}"

          # Using the backend repository as the source for RC version calculation
          API_URL="${REGISTRY_URL}/api/v2.0/projects/baron_sso/repositories/backend/artifacts?sort=-creation_time&page_size=100"

          AUTH_HEADER=$(echo -n "${HARBOR_USER}:${HARBOR_PASSWORD}" | base64)
          API_RESPONSE=$(curl -s -k -H "Authorization: Basic ${AUTH_HEADER}" "${API_URL}")

          # Define a search pattern to find RCs across different months for the same major/minor version
          # e.g., matches v1.2508.1-RC, v1.2509.1-RC, etc.
          SEARCH_PATTERN="^${MAJOR_VERSION}\.[0-9]{4}\.${MINOR_VERSION}-RC"
          echo "Using search pattern: ${SEARCH_PATTERN}"

          # Disable pipefail for grep, as it will exit with 1 if no match is found
          set +o pipefail
          # Find the highest RC number regardless of the YYMM part
          LATEST_RC_NUM=$(echo "${API_RESPONSE}" | jq -r '.[] | .tags[]? | .name' | grep -E "${SEARCH_PATTERN}" | sed 's/.*-RC//' | sort -rn | head -n 1)
          set -o pipefail

          if [ -z "$LATEST_RC_NUM" ]; then
            NEXT_RC_NUM=1
          else
            NEXT_RC_NUM=$((LATEST_RC_NUM + 1))
          fi

          # Create the new tag using the dynamically generated BASE_TAG and the incremented RC number
          NEW_RC_TAG="${BASE_TAG}-RC${NEXT_RC_NUM}"
          echo "new_rc_tag=$NEW_RC_TAG" >> $GITHUB_OUTPUT
          echo "Found latest RC number: ${LATEST_RC_NUM:-0}"
          echo "Calculated new RC tag: $NEW_RC_TAG"

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

      - name: Build and push backend RC image
        uses: docker/build-push-action@v5
        with:
          context: ./backend
          file: ./backend/Dockerfile
          push: true
          tags: ${{ vars.HARBOR_HOSTNAME }}/baron_sso/backend:${{ steps.rc_calculator.outputs.new_rc_tag }}
          provenance: false
          sbom: false

      - name: Build and push adminfront RC image
        uses: docker/build-push-action@v5
        with:
          context: ./adminfront
          file: ./adminfront/Dockerfile
          push: true
          tags: ${{ vars.HARBOR_HOSTNAME }}/baron_sso/adminfront:${{ steps.rc_calculator.outputs.new_rc_tag }}
          provenance: false
          sbom: false

      - name: Build and push devfront RC image
        uses: docker/build-push-action@v5
        with:
          context: ./devfront
          file: ./devfront/Dockerfile
          push: true
          tags: ${{ vars.HARBOR_HOSTNAME }}/baron_sso/devfront:${{ steps.rc_calculator.outputs.new_rc_tag }}
          provenance: false
          sbom: false

      - name: Build and push orgfront RC image
        uses: docker/build-push-action@v5
        with:
          context: ./orgfront
          file: ./orgfront/Dockerfile
          push: true
          tags: ${{ vars.HARBOR_HOSTNAME }}/baron_sso/orgfront:${{ steps.rc_calculator.outputs.new_rc_tag }}
          provenance: false
          sbom: false

      - name: Build and push userfront RC image
        uses: docker/build-push-action@v5
        with:
          context: ./userfront
          file: ./userfront/Dockerfile
          push: true
          tags: ${{ vars.HARBOR_HOSTNAME }}/baron_sso/userfront:${{ steps.rc_calculator.outputs.new_rc_tag }}
          provenance: false
          sbom: false
