name: github-query
description: "Make a query to GitHub."
inputs:
  url:
    description: "Url of the GitHub server repository."
    required: true
    default: ${{ github.server_url }}
  route:
    description: "Route of the api to call."
    required: false
    default: ""
  apiToken:
    description: "Api Token to for GitHub."
    required: false
    default: ${{ github.token }}
  additionalArgs:
    description: "Additional arguments to pass into curl."
    required: false
outputs:
  query:
    description: "The query result."
    value: ${{ steps.query.outputs.console }}
runs:
  using: "composite"
  steps:
  - name: "Build and run query."
    id: query
    run: |
      URL_ROOT="${{ inputs.url }}"
      # Remove any trailing slash from the url root
      URL_ROOT=${URL_ROOT%/}
      # Remove any leading slash from the route
      ROUTE="${{ inputs.route }}"
      ROUTE=${ROUTE#/}

      FULL_URL="$URL_ROOT/$ROUTE"

      QUERY="curl -sL \"$FULL_URL\" ${{ inputs.additionalArgs }}"

      TOKEN="${{ inputs.apiToken }}"
      if [[ -n "$TOKEN" ]]; then
        QUERY="$QUERY -H \"Authorization: token $TOKEN\""
      fi
      
      OUTPUT=$(eval "$QUERY")
      RESULT=$?
      
      if [[ -n "$OUTPUT" ]]; then
        echo "console<<EOF" >> "$GITHUB_OUTPUT"
        echo "$OUTPUT" >> "$GITHUB_OUTPUT"
        echo "EOF" >> "$GITHUB_OUTPUT"
      fi
      exit $RESULT
    shell: bash