name: 'CCache Setup'
description: 'Run a Bazel-based docker image for Protobuf CI testing'
inputs:
  cache-prefix:
    required: true
    description: A unique prefix to prevent cache pollution
    type: string
  support-modules:
    required: false
    description: Whether or not we need to support modules.  This can result in extra cache misses.

runs:
  using: 'composite'
  steps:
    - name: Configure ccache environment variables
      shell: bash
      run: |
        echo "CCACHE_BASEDIR=${{ github.workspace }}" >> $GITHUB_ENV
        echo "CCACHE_DIR=${{ github.workspace }}/.ccache" >> $GITHUB_ENV
        echo "CCACHE_COMPRESS=true" >> $GITHUB_ENV
        echo "CCACHE_COMPRESSLEVEL=5" >> $GITHUB_ENV
        echo "CCACHE_MAXSIZE=100M" >> $GITHUB_ENV
        echo "CCACHE_SLOPPINESS=clang_index_store,include_file_ctime,include_file_mtime,file_macro,time_macros" >> $GITHUB_ENV
        echo "CCACHE_DIRECT=true" >> $GITHUB_ENV
        echo "CCACHE_CMAKE_FLAGS=-Dprotobuf_ALLOW_CCACHE=ON -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache" >> $GITHUB_ENV

    - name: Setup ccache on Windows
      if: ${{ runner.os == 'Windows' }}
      uses: ./.github/actions/internal/ccache-setup-windows
    - name: Setup ccache on Mac
      if: ${{ runner.os == 'macOS' }}
      shell: bash
      run: brew install ccache

    - name: Setup fixed path ccache caching
      uses: actions/cache@627f0f41f6904a5b1efbaed9f96d9eb58e92e920 # v3.2.4
      with:
        path: |
          .ccache/**
          !.ccache/lock
          !.ccache/tmp
        # Always push to a cache key unique to this commit.
        key: ${{ format('ccache-{0}-{1}-{2}', inputs.cache-prefix, github.ref_name, github.sha) }}
        # Select a cache to restore from with the follow order of preference:
        # 1) The exact same commit we're running over
        # 2) The latest cache from the current ref branch
        # 3) The latest push to the base ref of a pull request
        restore-keys: |
          ${{ format('ccache-{0}-{1}-{2}', inputs.cache-prefix, github.ref_name, github.sha) }}
          ${{ format('ccache-{0}-{1}', inputs.cache-prefix, github.ref_name) }}
          ${{ format('ccache-{0}-{1}', inputs.cache-prefix, github.base_ref) }}

    - name: Enable module support
      if: ${{ inputs.support-modules }}
      shell: bash
      run: |
        echo "CCACHE_SLOPPINESS=$CCACHE_SLOPPINESS,modules" >> $GITHUB_ENV
        echo "CCACHE_DEPEND=true" >> $GITHUB_ENV

    - name: Zero out ccache
      if: ${{ runner.os != 'Linux' }}
      shell: bash
      run: ccache -z
