name: Send a message to slack

inputs:
  msg:
    description: The slack message text
  slack_url:
    description: passthrough for secrets.SLACK_WEBHOOK_URL

runs:
  using: composite
  steps:
    - uses: actions/checkout@v3

    - name: set github ref
      shell: bash
      run: |
        echo "github_reference=${{ github.ref }}" >> $GITHUB_ENV

    - name: trim github ref
      shell: bash
      run: |
        echo "trimmed_ref=${github_reference#refs/}" >> $GITHUB_ENV
    
    - name: build urls
      shell: bash
      run: |
        echo "logurl=$(printf '<https://github.com/alcionai/corso/actions/runs/%s|[Action]>' ${{ github.run_id }})" >> $GITHUB_ENV
        echo "commiturl=$(printf '<https://github.com/alcionai/corso/commit/%s|[Commit]>' ${{ github.sha }})" >> $GITHUB_ENV
        echo "refurl=$(printf '<https://github.com/alcionai/corso/%s|[Ref]>' ${{ env.trimmed_ref }})" >> $GITHUB_ENV

    - name: use url or blank val
      shell: bash
      run: |
        echo "STEP=${{ github.action || '' }}" >> $GITHUB_ENV
        echo "JOB=${{ github.job || '' }}" >> $GITHUB_ENV
        echo "LOGS=${{ github.run_id && env.logurl || '-' }}" >> $GITHUB_ENV
        echo "COMMIT=${{ github.sha && env.commiturl || '-' }}" >> $GITHUB_ENV
        echo "REF=${{ env.trimmed_ref && env.refurl || '-' }}" >> $GITHUB_ENV

    - id: slack-message
      uses: slackapi/slack-github-action@v1.24.0
      env:
        SLACK_WEBHOOK_URL: ${{ inputs.slack_url }}
        SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK
      with:
        payload: |
          {
            "text": "${{ inputs.msg }} :: ${{ env.LOGS }} ${{ env.COMMIT }} ${{ env.REF }}",
            "blocks": [
              {
                "type": "section",
                "text": {
                  "type": "mrkdwn",
                  "text": "${{ inputs.msg }} :: ${{ env.JOB }} - ${{ env.STEP }}\n${{ env.LOGS }} ${{ env.COMMIT }} ${{ env.REF }}"
                }
              }
            ]
          }
