name: Build Cache Key

description: >
  Generates a cache key suitable for save/restore of Kong builds.

inputs:
  prefix:
    description: 'String prefix applied to the build cache key'
    required: false
    default: 'build'
  extra:
    description: 'Additional values/file hashes to use in the cache key'
    required: false

outputs:
  cache-key:
    description: 'The generated cache key'
    value: ${{ steps.cache-key.outputs.CACHE_KEY }}

runs:
  using: composite
  steps:
    - name: Generate cache key
      id: cache-key
      shell: bash
      env:
        PREFIX: ${{ inputs.prefix }}
        EXTRA: ${{ inputs.extra }}
      run: |
        # please keep these sorted
        FILE_HASHES=(
          ${{ hashFiles('.bazelignore') }}
          ${{ hashFiles('.bazelrc') }}
          ${{ hashFiles('.bazelversion') }}
          ${{ hashFiles('.github/actions/build-cache-key/**') }}
          ${{ hashFiles('.github/workflows/build.yml') }}
          ${{ hashFiles('.requirements') }}
          ${{ hashFiles('BUILD.bazel') }}
          ${{ hashFiles('WORKSPACE') }}
          ${{ hashFiles('bin/kong') }}
          ${{ hashFiles('bin/kong-health') }}
          ${{ hashFiles('build/**') }}
          ${{ hashFiles('kong-*.rockspec') }}
          ${{ hashFiles('kong.conf.default') }}
        )

        if [[ -n ${EXTRA:-} ]]; then
          readarray \
            -O "${#FILE_HASHES[@]}" \
            -t \
            FILE_HASHES \
          <<< "$EXTRA"
        fi

        HASH=$(printf '%s\n' "${FILE_HASHES[@]}" \
          | grep -vE '^$' \
          | sort --stable --unique \
          | sha256sum - \
          | awk '{print $1}'
        )

        echo "CACHE_KEY=${PREFIX}::${HASH}" | tee -a $GITHUB_OUTPUT
