name: versionsapi
description: "A GitHub Action to interact with the versions API"

#
# !!! Attention !!!
#
# Calls with command 'add' and 'remove' need synchronization.
# Don't use this action directly for these commands.
# Use the 'versionsapi' workflow instead.
#

inputs:
  command:
    description: Command to run
    required: true
  ref:
    description: --ref flag
    required: false
  stream:
    description: --stream flag
    required: false
  version:
    description: --version flag
    required: false
  kind:
    description: --kind flag
    required: false
  version_path:
    description: --version-path flag
    required: false
  add_latest:
    description: --latest flag (boolean)
    required: false
    default: "false"
  add_release:
    description: --release flag (boolean)
    required: false
    default: "false"
  rm_all:
    description: --all flag (boolean)
    required: false
    default: "false"
  dryrun:
    description: --dryrun flag (boolean)
    required: false
    default: "false"
outputs:
  output:
    description: Output of the command
    value: ${{ steps.run.outputs.output }}

runs:
  using: composite
  steps:
    - name: Get versionsapi binary
      shell: bash
      run: |
        containerID=$(docker create "ghcr.io/edgelesssys/constellation/versionsapi-ci-cli:latest")
        docker cp ${containerID}:/versionsapi .

    - name: Run versionsapi
      id: run
      shell: bash
      run: |
        out=$(
          ./versionsapi \
            ${{ inputs.command }} \
            ${{ inputs.ref != '' && format('--ref="{0}"', inputs.ref) || '' }} \
            ${{ inputs.stream != '' && format('--stream="{0}"', inputs.stream) || '' }} \
            ${{ inputs.version != '' && format('--version="{0}"', inputs.version) || '' }} \
            ${{ inputs.kind != '' && format('--kind="{0}"', inputs.kind) || '' }} \
            ${{ inputs.version_path != '' && format('--version-path="{0}"', inputs.version_path) || '' }} \
            ${{ inputs.add_latest == 'true' && '--latest' || '' }} \
            ${{ inputs.add_release == 'true' && '--release' || '' }} \
            ${{ inputs.rm_all == 'true' && '--all' || '' }} \
            ${{ inputs.dryrun == 'true' && '--dryrun' || '' }}
        )

        # Multiline output is not supported by GitHub Actions,
        # and if we encode it, it is redacted as secret. 🤦
        # So we have to workaround by writing it to a file.

        if [[ ${{ inputs.command }} == 'list' ]]; then
          echo "$out" > versionsapi_output.txt
          exit 0
        fi

        echo "output=${out}" | tee -a "$GITHUB_OUTPUT"