name: Services Validator

on:
  push:
    paths:
      - "plugins/rtmp-services/data/services.json"
      - "plugins/rtmp-services/data/package.json"
  pull_request:
    paths:
      - "plugins/rtmp-services/data/services.json"
      - "plugins/rtmp-services/data/package.json"
  schedule:
  - cron: 0 0 * * *
  workflow_dispatch:

jobs:
  schema:
    name: Schema
    runs-on: [ubuntu-20.04]
    if: ${{ github.repository_owner == 'obsproject' || github.event_name != 'schedule' }}
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Install & Configure Python
        run: |
          sudo apt install python3.9-dev
          python3.9 -m pip install jsonschema json_source_map

      - name: Validate Service JSON Schema
        run: |
          JSON_FILES=(
            plugins/rtmp-services/data/services.json
            plugins/rtmp-services/data/package.json
          )
          python3.9 CI/check-jsonschema.py "${JSON_FILES[@]}"

      - name: Annotate Errors
        if: failure()
        uses: yuzutech/annotations-action@v0.4.0
        with:
          repo-token: "${{ secrets.GITHUB_TOKEN }}"
          title: "Service JSON Errors"
          input: "./validation_errors.json"

  service_check:
    name: Service Check
    runs-on: ubuntu-20.04
    needs: schema
    if: ${{ github.repository_owner == 'obsproject' && github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }}

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

      - name: Restore cache
        uses: actions/cache@v3
        with:
          path: ${{ github.workspace }}/other
          # Workaround to create a new cache every time, since a cache key is immutable:
          # https://github.com/actions/cache/blob/main/workarounds.md#update-a-cache
          key: service-check-${{ github.run_id }}
          restore-keys: service-check

      - name: Install & Configure Python
        run: |
          sudo apt install python3.9
          python3.9 -m pip install requests

      - name: Check Services
        id: check
        run: python3.9 -u CI/check-services.py
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          WORKFLOW_RUN_ID: ${{ github.run_id }}
          REPOSITORY: ${{ github.repository }}

      - uses: actions/upload-artifact@v3
        with:
          name: timestamps
          path: ${{ github.workspace }}/other/*

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@f094b77505fb89581e68a1163fbd2fffece39da1
        if: steps.check.outputs.make_pr == 'true'
        with:
          author: "Service Checker <commits@obsproject.com>"
          commit-message: "rtmp-services: Remove defunct servers/services"
          title: "rtmp-services: Remove defunct servers/services"
          branch: "automated/clean-services"
          body: ${{ fromJSON(steps.check.outputs.pr_message) }}
          delete-branch: true
