name: 'CCache Setup'
description: 'Setup ccache for us in Windows CI'
inputs:
  ccache-version:
    required: false
    default: '4.7.4'
    description: A pinned version of ccache
    type: string

runs:
  using: 'composite'
  steps:
    - name: Setup MSVC
      uses: ilammy/msvc-dev-cmd@cec98b9d092141f74527d0afa6feb2af698cfe89 # v1.12.1
      with:
        arch: x64
        vsversion: '2019'

    - name: Setup ccache path
      shell: bash
      run: |
        echo "CCACHE_EXE_PATH=$LOCALAPPDATA\ccache-${{ inputs.ccache-version }}-windows-x86_64" >> $GITHUB_ENV
        echo "$LOCALAPPDATA\ccache-${{ inputs.ccache-version }}-windows-x86_64" >> $GITHUB_PATH

    - name: Add ccache to Powershell path
      shell: pwsh
      run: echo "%LOCALAPPDATA%\ccache-${{ inputs.ccache-version }}-windows-x86_64" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append

    - name: Setup caching of ccache download
      if: ${{ github.event_name != 'pull_request' && github.event_name != 'pull_request_target' }}
      id: ccache-cache
      uses: actions/cache@627f0f41f6904a5b1efbaed9f96d9eb58e92e920 # v3.2.4
      with:
        path: ${{ env.CCACHE_EXE_PATH }}
        key: ccache-exe-${{ inputs.ccache-version }}

    - name: Restore ccache download
      if: ${{ github.event_name == 'pull_request' || github.event_name == 'pull_request_target' }}
      id: ccache-restore
      uses: actions/cache/restore@627f0f41f6904a5b1efbaed9f96d9eb58e92e920 # v3.2.4
      with:
        path: ${{ env.CCACHE_EXE_PATH }}
        key: ccache-exe-${{ inputs.ccache-version }}

    - name: Download ccache
      shell: bash
      if: ${{ steps.ccache-cache.outputs.cache-hit != 'true' && steps.ccache-restore.outputs.cache-hit != 'true'}}
      run: |
        cd $LOCALAPPDATA
        curl -kLSs "https://github.com/ccache/ccache/releases/download/v${{ inputs.ccache-version }}/ccache-${{ inputs.ccache-version }}-windows-x86_64.zip" -o ccache.zip
        unzip ccache.zip
        rm ccache.zip
        ccache --version

    - name: Configure ccache environment variables
      shell: pwsh
      run: |
        Write-Host $Env:GITHUB_REF
        $cllocation = (Get-Command cl.exe).Path
        echo "CCACHE_COMPILER=$cllocation" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf8 -Append
        echo "CCACHE_COMPILERTYPE=msvc" | Out-File -FilePath $Env:GITHUB_ENV -Encoding utf8 -Append

    - name: Configure Windows-specific ccache environment variables
      shell: bash
      # Windows caches are about 2x larger than other platforms.
      run: |
        echo "CCACHE_COMPRESSLEVEL=10" >> $GITHUB_ENV
        echo "CCACHE_MAXSIZE=200M" >> $GITHUB_ENV
