name: List Unhealthy Branches

on:
  schedule:
    - cron: '0 3 * * fri'

jobs:
  list:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0

    - uses: actions/setup-node@v3
      with:
        node-version: '16'

    - name: List branches
      id: list-branches
      run: |
        export SLACK_ATTACHMENTS_ILLEGAL=`node bin/github-actions/list-branches --illegal`
        export SLACK_ATTACHMENTS_INACTIVE=`node bin/github-actions/list-branches --inactive`
        echo "SLACK_ATTACHMENTS_ILLEGAL=$SLACK_ATTACHMENTS_ILLEGAL" >> $GITHUB_OUTPUT
        echo "SLACK_ATTACHMENTS_INACTIVE=$SLACK_ATTACHMENTS_INACTIVE" >> $GITHUB_OUTPUT
        echo "SLACK_ATTACHMENTS_LENGTH_ILLEGAL=$(echo $SLACK_ATTACHMENTS_ILLEGAL | jq '. | length')" >> $GITHUB_OUTPUT
        echo "SLACK_ATTACHMENTS_LENGTH_INACTIVE=$(echo $SLACK_ATTACHMENTS_INACTIVE | jq '. | length')" >> $GITHUB_OUTPUT

    - name: Slack Notification for illegal named branches
      if: steps.list-branches.outputs.SLACK_ATTACHMENTS_LENGTH_ILLEGAL > 0
      uses: sonots/slack-notice-action@v3
      env:
        SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
      with:
        status: custom
        payload: |
          {
            text: '<!channel> There is some branches *with illegal names* on GitHub.',
            channel: '#ci',
            attachments: ${{ steps.list-branches.outputs.SLACK_ATTACHMENTS_ILLEGAL }}
          }

    - name: Slack Notification for inactive branches
      if: steps.list-branches.outputs.SLACK_ATTACHMENTS_LENGTH_INACTIVE > 0
      uses: sonots/slack-notice-action@v3
      env:
        SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
      with:
        status: custom
        payload: |
          {
            text: '<!channel> There is some branches *that are no longer updated* on GitHub.',
            channel: '#ci',
            attachments: ${{ steps.list-branches.outputs.SLACK_ATTACHMENTS_INACTIVE }}
          }
