name: 'Tiles File'
on:
  workflow_dispatch:
    inputs:
      file_name:
        description: 'The name of the file to deploy, defaults to newest file'
        required: false
#  pull_request:
#    branches: [ "main" ]
#    paths:
#      - ".github/workflows/tiles-file.yml"
#      - "map-styles/**"

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

jobs:
  deploy_tiles:
    name: Deploy Tiles & Styles
    defaults:
      run:
        working-directory: 'map-styles'
    runs-on: mich
    outputs:
      KEY: ${{ steps.latest_build.outputs.KEY }}
    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          submodules: 'recursive'

      - name: Setup Node
        uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
        with:
          node-version-file: 'map-styles/.nvmrc'

      - name: Install dependencies
        run: npm ci

      - name: Generate styles
        run: npm run build

      - name: Find latest pmtiles build
        id: latest_build
        env:
          FILE_NAME: ${{ github.event.inputs.file_name }}
        run: |
          if [ -z "$FILE_NAME" ]; then
            build=$(curl -s https://build-metadata.protomaps.dev/builds.json | jq -r 'map(.key) | sort | last')
          else
            build=$FILE_NAME
          fi
          export build=${build%.pmtiles}
          echo "KEY=$build"
          echo "KEY=$build" >> $GITHUB_OUTPUT

      - name: Install GH CLI
        uses: dev-hanz-ops/install-gh-cli-action@af38ce09b1ec248aeb08eea2b16bbecea9e059f8 # v0.2.1

      - name: Setup Rclone
        uses: AnimMouse/setup-rclone@26ef2133e09fd383329a1d4c1fbe6a71db1976c9 # v1.12.0
        with:
          disable_base64: true
          rclone_config: |
            [r2]
            type = s3
            provider = Cloudflare
            region = auto
            endpoint = https://601adaaa1eab190cdfe2945f9a6c89d0.r2.cloudflarestorage.com
            access_key_id = ${{ secrets.CLOUDFLARE_TILES_R2_KV_TOKEN_ID }}
            secret_access_key = ${{ secrets.CLOUDFLARE_TILES_R2_KV_TOKEN_HASHED_VALUE }}
            [pmtiles]
            type = http
            url = https://build.protomaps.com/

      - name: Download latest tiles from build server
        run: |
          sudo apt-get update
          sudo apt-get install aria2 -y
          aria2c --continue=true -s16 -x16 -j16 --summary-interval=10 --remote-time=true --file-allocation=none https://build.protomaps.com/${{ steps.latest_build.outputs.KEY }}.pmtiles -d ./dist/ -o tiles.pmtiles

      - name: Copy latest tiles to R2
        run: |
          regions="wnam oc weur apac eeur enam"
          key="${{ steps.latest_build.outputs.KEY }}"
          source_folder="./dist/"

          for region in $regions; do
            dest="r2:/tiles-${region}/${key}/"
            echo "--- Starting parallel upload to $dest ---"
            (
              rclone --progress copyto "$source_folder" "$dest" \
                --s3-no-check-bucket \
                --ignore-checksum \
                --s3-disable-checksum \
                --s3-upload-cutoff=100M \
                --transfers 1 \
                --s3-upload-concurrency 25 \
                --s3-chunk-size=100M \
                --multi-thread-streams=25 \
                --checkers=64 2>&1 | sed "s/^/[${region}] /"
            ) &
          done

          wait # Wait for all background rclone processes to finish
          echo "--- All parallel uploads completed. ---"
  update_tile_ref:
    name: Update tile server file reference
    needs: [deploy_tiles]
    runs-on: ubuntu-latest
    steps:
      - name: Generate a token
        id: generate-token
        uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3
        with:
          app-id: ${{ secrets.PUSH_O_MATIC_APP_ID }}
          private-key: ${{ secrets.PUSH_O_MATIC_APP_KEY }}
      - name: 'Checkout'
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          ref: ${{ github.event.pull_request.head.ref }}
          token: ${{ steps.generate-token.outputs.token }}

      - name: Update deployment file name
        run: |
          sed -i -E 's/"pmtiles_deployment_key": "(.*)"/"pmtiles_deployment_key": "${{ needs.deploy_tiles.outputs.KEY }}"/' deployment/modules/cloudflare/tiles-worker/tiles.tfvars.json

      - name: Push updated tiles.tfvars to repo
        uses: EndBug/add-and-commit@290ea2c423ad77ca9c62ae0f5b224379612c0321 # v10.0.0
        with:
          add: deployment/modules/cloudflare/tiles-worker/tiles.tfvars.json
          message: Update tile server file to ${{ needs.deploy_tiles.outputs.KEY }}
          push: ${{ github.event_name == 'workflow_dispatch' }}
