name: Setup ESP-IDF Toolchain

inputs:
  toolchain:
    description: 'Toolchain name'
    required: true
  toolchain_version:
    description: 'Toolchain version'
    required: false
    default: 'v5.3.2'

runs:
  using: "composite"
  steps:
    - name: Set DOCKER_ESP_IDF
      run: |
        DOCKER_ESP_IDF=$HOME/cache/${{ inputs.toolchain }}/docker_image.tar
        echo "DOCKER_ESP_IDF=$DOCKER_ESP_IDF" >> $GITHUB_ENV
      shell: bash

    - name: Cache Docker Image
      uses: actions/cache@v4
      id: cache-toolchain-espressif
      with:
        path: ${{ env.DOCKER_ESP_IDF }}
        key: ${{ inputs.toolchain }}-${{ inputs.toolchain_version }}

    - name: Pull and Save Docker Image
      if: steps.cache-toolchain-espressif.outputs.cache-hit != 'true'
      run: |
        docker pull espressif/idf:${{ inputs.toolchain_version }}
        mkdir -p $(dirname $DOCKER_ESP_IDF)
        docker save -o $DOCKER_ESP_IDF espressif/idf:${{ inputs.toolchain_version }}
        du -sh $DOCKER_ESP_IDF
      shell: bash

    - name: Load Docker Image
      if: steps.cache-toolchain-espressif.outputs.cache-hit == 'true'
      run: |
        du -sh $DOCKER_ESP_IDF
        docker load --input $DOCKER_ESP_IDF
      shell: bash

    - name: Tag Local Image
      run: |
        docker tag espressif/idf:${{ inputs.toolchain_version }} espressif/idf:tinyusb
        docker images
      shell: bash
