name: Select image
description: Resolve string presets and shortpaths to shortpaths only

inputs:
  osImage:
    description: "Shortpath or main-debug or release-stable"
    required: true

outputs:
  osImage:
    description: "Shortpath of for input string, original input if that was already a shortpath"
    value: ${{ steps.set-output.outputs.osImage }}
  isDebugImage:
    description: "Input represents a debug image or not"
    value: ${{ steps.set-output.outputs.isDebugImage }}

runs:
  using: "composite"
  steps:
    - name: Login to AWS
      uses: aws-actions/configure-aws-credentials@010d0da01d0b5a38af31e9c3470dbfdabdecca3a # v4.0.1
      with:
        role-to-assume: arn:aws:iam::795746500882:role/GithubConstellationVersionsAPIRead
        aws-region: eu-central-1

    - name: Input is preset
      id: input-is-preset
      shell: bash
      run: |
        if [[ "${{ inputs.osImage }}" == "ref/main/stream/debug/?" || "${{ inputs.osImage }}" == "ref/release/stream/stable/?" ]]; then
          echo "result=true" | tee -a "$GITHUB_OUTPUT"
        else
          echo "result=false" | tee -a "$GITHUB_OUTPUT"
        fi

    - name: Separate ref and stream from matrix
      if: steps.input-is-preset.outputs.result == 'true'
      id: separate-ref-stream
      env:
        REFSTREAM: ${{ inputs.osImage }}
      shell: bash
      run: |
        echo "ref=$(echo $REFSTREAM | cut -d/ -f2)" | tee -a "$GITHUB_OUTPUT"
        echo "stream=$(echo $REFSTREAM | cut -d/ -f4)" | tee -a "$GITHUB_OUTPUT"

    - name: Find latest image
      if: steps.input-is-preset.outputs.result == 'true'
      id: find-latest-image
      uses: ./.github/actions/versionsapi
      with:
        command: latest
        ref: ${{ steps.separate-ref-stream.outputs.ref == 'release' && '-' || steps.separate-ref-stream.outputs.ref }}
        stream: ${{ steps.separate-ref-stream.outputs.stream }}

    - name: Set outputs
      id: set-output
      shell: bash
      run: |
        if [[ ${{ steps.input-is-preset.outputs.result }} == "true" ]]
        then
          export IMAGE=${{ steps.find-latest-image.outputs.output }}
        else
          export IMAGE=${{ inputs.osImage }}
        fi

        echo "osImage=$IMAGE" | tee -a "$GITHUB_OUTPUT"
        echo "Using image: $IMAGE"

        case "$IMAGE" in
          *"/stream/debug/"*)
            echo "isDebugImage=true" | tee -a "$GITHUB_OUTPUT"
            echo "Image is debug image."
            ;;
          *)
            echo "isDebugImage=false" | tee -a "$GITHUB_OUTPUT"
            echo "Image is not debug image."
            ;;
        esac
