name: Read Metalhost monitoring
on:
  workflow_dispatch:
permissions: {}
jobs:
  monitoring:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      id-token: write
    env:
      # Copy these non-secret values from the approved Metalhost connection.
      METALHOST_ENDPOINT: ${{ vars.METALHOST_ENDPOINT }}
      METALHOST_TRUST: ${{ vars.METALHOST_TRUST }}
      METALHOST_AUDIENCE: ${{ vars.METALHOST_AUDIENCE }}
    steps:
      - name: Exchange GitHub identity and read VM inventory
        shell: bash
        run: |
          set -euo pipefail
          set +x
          : "${METALHOST_ENDPOINT:?Set the API origin for your enabled environment}"
          : "${METALHOST_TRUST:?Set the approved trust name}"
          : "${METALHOST_AUDIENCE:?Set the connection audience}"
          case "$METALHOST_ENDPOINT" in
            https://*) ;;
            *) echo 'An HTTPS API origin is required' >&2; exit 1 ;;
          esac
          audience=$(jq -rn --arg value "$METALHOST_AUDIENCE" '$value|@uri')
          assertion=$(curl --fail --silent --show-error --max-time 30 \
            -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
            "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$audience" | jq -er '.value')
          echo "::add-mask::$assertion"
          response=$(jq -nc --arg trust "$METALHOST_TRUST" --arg assertion "$assertion" \
            '{trustName:$trust,assertion:$assertion}' |
            curl --fail --silent --show-error --max-time 30 \
              -H 'Content-Type: application/json' -H 'Connect-Protocol-Version: 1' \
              --data-binary @- "$METALHOST_ENDPOINT/aes.iam.v1.AutomationService/ExchangeGitHubToken")
          token=$(jq -er '.accessToken' <<<"$response")
          echo "::add-mask::$token"
          project=$(jq -er '.projectName' <<<"$response")
          unset assertion response
          # Requires monitoring.read. This request does not create or change VMs.
          jq -nc --arg project "$project" \
            '{projectName:$project,pageSize:50,inventoryOnly:true}' |
            curl --fail --silent --show-error --max-time 30 \
              -H "Authorization: Bearer $token" \
              -H 'Content-Type: application/json' -H 'Connect-Protocol-Version: 1' \
              --data-binary @- "$METALHOST_ENDPOINT/aes.monitoring.v1.MonitoringService/ListVMMonitoring" |
            jq '{vms:[.vms[]? | {name,displayName,state}],nextPageToken}'
          unset token
