name: Checkout

inputs:
    fetch-depth:
        default: 1
        required: false
        type: number
    path:
        required: false
        type: string
    repository:
        default: ${{ github.repository }}
        required: false
        type: string
    ref:
        required: false
        type: string
    alternate_repository:
        required: false
        type: string
    alternate_ref:
        required: false
        type: string
    token:
        default: ${{ github.token }}
        required: false
        type: string

outputs:
    ref_exists:
        description: 'Specifies whether the ref exists or not'
        value: ${{ steps.repo.outputs.ref-exists }}

runs:
    using: composite

    steps:
        - id: repo
          shell: bash
          env:
              GH_TOKEN: ${{ inputs.token }}
              ALTERNATE_REF: ${{ inputs.alternate_ref }}
              REPOSITORY: ${{ inputs.repository }}
              REF: ${{ inputs.ref }}
          run: |
              if git ls-remote --heads --quiet --exit-code https://$GH_TOKEN@github.com/$REPOSITORY.git $REF
              then
                echo "::notice::Checkout: $REPOSITORY using $REF"
                echo "ref-exists=true" >> $GITHUB_OUTPUT
              else
                echo "::notice::Checkout: $REPOSITORY does not have ref  $REF (fallback to $ALTERNATE_REF)"
                echo "ref-exists=false" >> $GITHUB_OUTPUT
              fi

        - if: steps.repo.outputs.ref-exists == 'true'
          uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846
          env:
              REPO_PATH: ${{ inputs.path }}
              GH_TOKEN: ${{ inputs.token }}
              REPOSITORY: ${{ inputs.repository }}
              FETCH_DEPTH: ${{ inputs.fetch-depth }}
              REF: ${{ inputs.ref }}
          with:
              fetch-depth: ${{ env.FETCH_DEPTH }}
              path: ${{ env.REPO_PATH }}
              repository: ${{ env.REPOSITORY }}
              ref: ${{ env.REF }}
              token: ${{ env.GH_TOKEN }}

        - if: steps.repo.outputs.ref-exists == 'false'
          uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846
          env:
              REPO_PATH: ${{ inputs.path }}
              GH_TOKEN: ${{ inputs.token }}
              ALTERNATE_REF: ${{ inputs.alternate_ref }}
              ALTERNATE_REPOSITORY: ${{ inputs.alternate_repository }}
              FETCH_DEPTH: ${{ inputs.fetch-depth }}
          with:
              fetch-depth: ${{ env.FETCH_DEPTH }}
              path: ${{ env.REPO_PATH }}
              repository: ${{ env.ALTERNATE_REPOSITORY }}
              ref: ${{ env.ALTERNATE_REF }}
              token: ${{ env.GH_TOKEN }}
