on:
  workflow_call:
    inputs:
      dockerize:
        default: true
        type: boolean
      uploadJavaScriptArtifacts:
        required: true
        type: boolean
      publishLatest:
        default: false
        type: boolean
      build:
        default: true
        type: boolean
      targets:
        required: true
        type: string
      registry:
        default: ghcr.io
        type: string
      imageName:
        default: ${{ github.repository_owner }}
        type: string
      imageTag:
        required: true
        type: string
      publishSourceMaps:
        default: false
        type: boolean
      publishPrComment:
        default: true
        type: boolean

jobs:
  build-and-dockerize:
    runs-on: ubuntu-22.04
    permissions:
      contents: read
      packages: write
      pull-requests: write
    steps:
      - name: checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 2

      - name: setup environment
        if: ${{ inputs.build }}
        uses: ./.github/actions/setup
        with:
          actor: build-and-dockerize

      - name: build packages and applications
        if: ${{ inputs.build }}
        run: pnpm build

      - name: test ESM & CJS exports integrity
        if: ${{ inputs.build }}
        run: pnpm turbo check:build

      - uses: vimtor/action-zip@v1
        name: archive javascript artifacts
        if: ${{ inputs.uploadJavaScriptArtifacts }}
        with:
          recursive: false
          files:
            packages/services/broker-worker/dist/index.worker.mjs
            packages/services/cdn-worker/dist/index.worker.mjs
          dest: ${{ inputs.imageTag }}.zip

      - name: upload artifact
        uses: randomairborne/r2-release@v1.0.2
        with:
          endpoint: https://6d5bc18cd8d13babe7ed321adba3d8ae.r2.cloudflarestorage.com
          accesskeyid: ${{ secrets.R2_ACCESS_KEY_ID }}
          secretaccesskey: ${{ secrets.R2_SECRET_ACCESS_KEY }}
          bucket: hive-js-build-artifacts
          file: ${{ github.workspace }}/${{ inputs.imageTag }}.zip
          destination: ${{ inputs.imageTag }}.zip

      - name: upload app persisted documents artifact
        uses: randomairborne/r2-release@v1.0.2
        with:
          endpoint: https://6d5bc18cd8d13babe7ed321adba3d8ae.r2.cloudflarestorage.com
          accesskeyid: ${{ secrets.R2_ACCESS_KEY_ID }}
          secretaccesskey: ${{ secrets.R2_SECRET_ACCESS_KEY }}
          bucket: hive-js-build-artifacts
          file: ${{ github.workspace }}/packages/web/app/src/gql/persisted-documents.json
          destination: ${{ inputs.imageTag }}.app.documents.json

      - name: upload graphql schema
        uses: randomairborne/r2-release@v1.0.2
        with:
          endpoint: https://6d5bc18cd8d13babe7ed321adba3d8ae.r2.cloudflarestorage.com
          accesskeyid: ${{ secrets.R2_ACCESS_KEY_ID }}
          secretaccesskey: ${{ secrets.R2_SECRET_ACCESS_KEY }}
          bucket: hive-js-build-artifacts
          file: ${{ github.workspace }}/schema.graphql
          destination: ${{ inputs.imageTag }}.schema.graphqls

      - name: configure eqemu
        if: ${{ inputs.dockerize }}
        uses: docker/setup-qemu-action@v3
        with:
          platforms: 'linux/arm64,linux/amd64'

      - name: configure docker buildx
        if: ${{ inputs.dockerize }}
        uses: docker/setup-buildx-action@v3

      - name: login to docker registry
        if: ${{ inputs.dockerize }}
        uses: docker/login-action@v3
        with:
          registry: ${{ inputs.registry }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - uses: frabert/replace-string-action@v2.5
        id: branch_name_fix
        name: sanitize branch name
        if: ${{ inputs.dockerize }}
        with:
          pattern: '[+\/@|-]'
          flags: 'g'
          string: ${{ github.head_ref || github.ref_name }}
          replace-with: '_'

      - name: Prepare Bake inputs
        id: docker-bake-inputs
        run: |
          targets=$(docker buildx bake -f docker/docker.hcl --print build | jq -r '.group.build.targets[]')
          input_set=""
          first=0

          EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)

          echo "set<<$EOF" >> "$GITHUB_ENV"
          for target in $targets
          do
              echo "$target.cache-from=type=gha,ignore-error=true,scope=$GITHUB_REF-$target" >> "$GITHUB_ENV"
              echo "$target.cache-to=type=gha,ignore-error=true,mode=max,scope=$GITHUB_REF-$target" >> "$GITHUB_ENV"
          done
          echo "$EOF" >> "$GITHUB_ENV"

      - name: build docker images
        timeout-minutes: 360
        id: docker-bake
        if: ${{ inputs.dockerize }}
        uses: docker/bake-action@v5
        env:
          DOCKER_REGISTRY: ${{ inputs.registry }}/${{ inputs.imageName }}/
          COMMIT_SHA: ${{ inputs.imageTag }}
          RELEASE: ${{ inputs.imageTag }}
          BRANCH_NAME: ${{ steps.branch_name_fix.outputs.replaced }}
          BUILD_TYPE: 'publish'
          PWD: ${{ github.workspace }}
          BUILD_STABLE: ${{ inputs.publishLatest && '1' || '' }}
        with:
          # See https://github.com/docker/buildx/issues/1533
          provenance: false
          push: true
          files: docker/docker.hcl
          targets: ${{ inputs.targets }}
          set: |
            ${{ steps.docker-bake-inputs.outputs.set }}

      - name: docker details pr comment
        uses: marocchino/sticky-pull-request-comment@v2
        if:
          ${{ inputs.dockerize && github.event_name == 'pull_request' && inputs.publishPrComment }}
        with:
          message: |
            🐋 This PR was built and pushed to the following [Docker images](https://github.com/graphql-hive?ecosystem=container&tab=packages&visibility=public) (tag: `${{ inputs.imageTag }}`):

            <details>
              <summary>Docker Bake metadata</summary>
              
              ```json
              ${{ steps.docker-bake.outputs.metadata }}
              ```
            </details>

      - name: upload sourcemaps to Sentry
        if: ${{ inputs.publishSourceMaps }}
        env:
          SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
          SENTRY_ORG: the-guild-z4
          SENTRY_PROJECT: graphql-hive
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
          SENTRY_RELEASE: ${{ inputs.imageTag }}
        run: pnpm upload-sourcemaps
