name: Setup ESP-IDF Toolchain

inputs:
  toolchain:
    description: 'Toolchain name'
    required: true
  toolchain_url:
    description: 'Toolchain URL or version'
    required: true

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_url }}

    - name: Pull and Save Docker Image
      if: steps.cache-toolchain-espressif.outputs.cache-hit != 'true'
      run: |
        docker pull espressif/idf:${{ inputs.toolchain_url }}
        mkdir -p $(dirname $DOCKER_ESP_IDF)
        docker save -o $DOCKER_ESP_IDF espressif/idf:${{ inputs.toolchain_url }}
        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
