name: Prepare Protobuf Cache
description: Restore or build the cached Protobuf installation.

inputs:
  protobuf-ref:
    description: Protobuf tag or commit to build.
    required: true
  mold-linker-flags:
    description: Linker flags used to force mold.
    required: true

runs:
  using: composite
  steps:
    - name: Restore Protobuf Cache
      id: restore-protobuf-cache
      uses: actions/cache/restore@v4
      with:
        path: |
          /usr/local/lib/libproto*
          /usr/local/lib/libabsl*
          /usr/local/lib/libutf8*
          /usr/local/lib/cmake/protobuf
          /usr/local/lib/cmake/absl
          /usr/local/lib/cmake/utf8_range
          /usr/local/include/google/protobuf
          /usr/local/include/absl
          /usr/local/include/utf8_range.h
          /usr/local/bin/protoc*
        key: protobuf-${{ runner.os }}-${{ inputs.protobuf-ref }}-v2
        restore-keys: |
          protobuf-${{ runner.os }}-${{ inputs.protobuf-ref }}-v2

    - name: Install Protobuf
      if: steps.restore-protobuf-cache.outputs.cache-hit != 'true'
      shell: bash
      run: |
        git clone --depth 1 --branch ${{ inputs.protobuf-ref }} https://github.com/protocolbuffers/protobuf protobuf
        cmake -S protobuf -B protobuf/build -G Ninja \
          -DCMAKE_BUILD_TYPE=Release \
          -Dprotobuf_BUILD_TESTS=OFF \
          -DCMAKE_EXE_LINKER_FLAGS="${{ inputs.mold-linker-flags }}" \
          -DCMAKE_SHARED_LINKER_FLAGS="${{ inputs.mold-linker-flags }}" \
          -DCMAKE_MODULE_LINKER_FLAGS="${{ inputs.mold-linker-flags }}"
        cmake --build protobuf/build
        sudo cmake --install protobuf/build
        rm -rf protobuf

    - name: Save Protobuf Cache
      if: steps.restore-protobuf-cache.outputs.cache-hit != 'true'
      uses: actions/cache/save@v4
      with:
        path: |
          /usr/local/lib/libproto*
          /usr/local/lib/libabsl*
          /usr/local/lib/libutf8*
          /usr/local/lib/cmake/protobuf
          /usr/local/lib/cmake/absl
          /usr/local/lib/cmake/utf8_range
          /usr/local/include/google/protobuf
          /usr/local/include/absl
          /usr/local/include/utf8_range.h
          /usr/local/bin/protoc*
        key: protobuf-${{ runner.os }}-${{ inputs.protobuf-ref }}-v2
