name: regenerate-protos-cron

on:
  schedule:
    - cron: "0 9-18 * * 1-5"
  workflow_dispatch:

jobs:
  check-for-new-version:
    outputs:
      new-version: ${{ steps.version.outputs.new-version }}
      current-version: ${{ steps.version.outputs.current-version }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - id: current-vega-version
        name: Get current version of vega generated against
        run: echo "version=$(cat ./vega-version.txt)" >> $GITHUB_OUTPUT
      - name: Test output
        run: echo ${{ steps.current-vega-version.outputs.version }}
      - id: version
        uses: vegaprotocol/github-action-get-vega-version@v0.0.2
        with:
          include-preview-versions: true
          previous-version: ${{ steps.current-vega-version.outputs.version }}
  regenerate-protos:
    needs: check-for-new-version
    if: needs.check-for-new-version.outputs.new-version == 'true'
    runs-on: ubuntu-latest
    steps:
      - run: echo ${{ needs.check-for-new-version.outputs.new-version }}
      - run: echo ${{ needs.check-for-new-version.outputs.current-version }}
      - uses: actions/checkout@v3
        with:
          submodules: true

      - name: Use Node.js LTS
        uses: actions/setup-node@v3
        with:
          node-version: "lts/*"
          registry-url: "https://registry.npmjs.org"
      - run: npm install
      # TODO inefficient. We now know the tag, so we only need to fetch the single tag we are generating against
      - run: git fetch --unshallow && git fetch --tags
        working-directory: vendor/vega
      - run: git checkout tags/${{ needs.check-for-new-version.outputs.current-version }}
        working-directory: vendor/vega
      - name: Install protoc
        uses: actions-gw/setup-protoc-to-env@v2
      - name: Regenerate
        run: |
          protoc \
          --plugin=protoc-gen-js="node_modules/.bin/protoc-plugin-js" \
          --js_out="." \
          -I "vendor/vega/protos/sources" \
          vega/commands/v1/transaction.proto
      - name: update version
        run: echo ${{ needs.check-for-new-version.outputs.current-version }} > ./vega-version.txt
      - uses: stefanzweifel/git-auto-commit-action@v5
        with:
          commit_message: "chore: update to vega version ${{ needs.check-for-new-version.outputs.current-version }}"
          commit_user_name: vega-ci-bot
          commit_user_email: vega-ci-bot@vega.xyz
          skip_fetch: true
          skip_checkout: true
          create_branch: true
          branch: chore/update-protos-to-${{ needs.check-for-new-version.outputs.current-version }}
      - name: create pull request
        run: gh pr create -B main -H chore/update-protos-to-${{ needs.check-for-new-version.outputs.current-version }} --title 'Update protos to version ${{ needs.check-for-new-version.outputs.current-version }}' --body 'Autocreated protos update'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
