name: Update generated files
on:
  workflow_dispatch: {}
  schedule:
    - cron: "0 5 * * Thu"

env:
  DEFAULT_BRANCH: main

jobs:
  update_aws_node:
    name: Update aws-node and open PR
    runs-on: ubuntu-latest
    container: weaveworks/eksctl-build:e4d6253ee946435478ef637a8feaf08baffa2327
    env:
      UPDATE_BRANCH: update-aws-node
      GOPRIVATE: ""
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - name: Cache go-build and mod
        uses: actions/cache@v3
        with:
          path: |
            ~/.cache/go-build/
            ~/go/pkg/mod/
          key: go-${{ hashFiles('go.sum') }}
          restore-keys: |
            go-
      - name: Update aws-node
        run: make update-aws-node
      - name: Commit changes
        id: commit
        run: |
          git checkout $DEFAULT_BRANCH
          git checkout -B $UPDATE_BRANCH
          git config user.name "weaveworksbot"
          git config user.email "weaveworksbot@users.noreply.github.com"
          git add -u
          if ! EDITOR=true git commit -m "Update aws-node"; then
            echo "::set-output name=changes::false"
            exit 0
          fi
          echo "::set-output name=changes::true"
          ! git diff --exit-code $DEFAULT_BRANCH HEAD
          git push --force-with-lease origin HEAD
      - uses: actions/github-script@v6.2.0
        name: Open PR to ${{env.DEFAULT_BRANCH}}
        if: ${{ steps.commit.outputs.changes }} == 'true'
        with:
          github-token: ${{ secrets.WEAVEWORKSBOT_TOKEN }}
          script: |
            const { data: pr } = await github.pulls.create({
              ...context.repo,
              title: "Update aws-node",
              head: "${{ env.UPDATE_BRANCH }}",
              base: "${{ env.DEFAULT_BRANCH }}",
            });
            await github.issues.addLabels({
              ...context.repo,
              issue_number: pr.number,
              labels: ["kind/improvement"],
            });
