name: arduino-stats

on:
  schedule:
    # run every day at 07:00 AM, 03:00 PM and 11:00 PM
    - cron: "0 7,15,23 * * *"
  workflow_dispatch:
  repository_dispatch:

jobs:
  push-stats:
    # This workflow is only of value to the arduino/arduino-ide repository and
    # would always fail in forks
    if: github.repository == 'arduino/arduino-ide'
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - uses: actions/setup-python@v2
        with:
          python-version: '3.x'

      - name: Fetch downloads count form Arduino CDN using AWS Athena
        id: fetch
        env:
          AWS_ACCESS_KEY_ID: ${{ secrets.STATS_AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.STATS_AWS_SECRET_ACCESS_KEY }}
          AWS_ATHENA_SOURCE_TABLE: ${{ secrets.STATS_AWS_ATHENA_SOURCE_TABLE }}
          AWS_ATHENA_OUTPUT_LOCATION: ${{ secrets.STATS_AWS_ATHENA_OUTPUT_LOCATION }}
          GITHUB_REPOSITORY: ${{ github.repository }}
        run: |
          pip install boto3 semver
          python .github/tools/fetch_athena_stats.py

      - name: Send metrics
        uses: masci/datadog@v1
        with:
          api-key: ${{ secrets.DD_API_KEY }}
          # Metrics input expects YAML but JSON will work just right.
          metrics: ${{steps.fetch.outputs.result}}

      - name: Report failure
        if: failure()
        uses: masci/datadog@v1
        with:
          api-key: ${{ secrets.DD_API_KEY }}
          events: |
            - title: "Arduino IDE stats failing"
              text: "Stats collection failed"
              alert_type: "error"
              host: ${{ github.repository }}
              tags:
                - "project:arduino-ide"
                - "cdn:downloads.arduino.cc"
                - "workflow:${{ github.workflow }}"
