name: Get the latest open-vm-tools release for main
on:
  schedule:
    - cron:  '0 7 * * 3'
  workflow_dispatch:

jobs:
  get-vmware-release:
    runs-on: ubuntu-latest
    steps:
      - name: Check out scripts
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.BOT_PR_TOKEN }}
          path: scripts
      - name: Figure out latest open-vm-tools release version
        id: openvmtools-latest-release
        run: |
          version=$(git ls-remote --tags 'https://github.com/vmware/open-vm-tools' | cut -f2 | sed -n "/refs\/tags\/stable-[0-9]*\.[0-9]*\.[0-9]*$/s/^refs\/tags\/stable-//p" | sort -ruV | head -n1)
          buildNumber=$(curl -sSL https://api.github.com/repos/vmware/open-vm-tools/releases/latest | jq -r '.assets[0].name' | sed -n "s/^open-vm-tools-${version}*-\([0-9]*\)\..*/\1/p")
          echo "BUILD_NUMBER=${buildNumber}" >>"${GITHUB_OUTPUT}"
          echo "VERSION_NEW=${version}" >>"${GITHUB_OUTPUT}"
      - name: Set up Flatcar SDK
        id: setup-flatcar-sdk
        env:
          WORK_SCRIPTS_DIR: "${{ github.workspace }}/scripts"
          CHANNEL: main
        run: scripts/.github/workflows/setup-flatcar-sdk.sh
      - name: Apply patch for main
        id: apply-patch-main
        env:
          GHA_SCRIPTS_DIR: "${{ github.workspace }}/scripts"
          WORK_SCRIPTS_DIR: "${{ github.workspace }}/scripts"
          BUILD_NUMBER: ${{ steps.openvmtools-latest-release.outputs.BUILD_NUMBER }}
          VERSION_NEW: ${{ steps.openvmtools-latest-release.outputs.VERSION_NEW }}
          PACKAGES_CONTAINER: ${{ steps.setup-flatcar-sdk.outputs.PACKAGES_CONTAINER }}
          SDK_NAME: ${{ steps.setup-flatcar-sdk.outputs.SDK_NAME }}
          TARGET_BRANCH: main
        run: scripts/.github/workflows/vmware-apply-patch.sh
      - name: Create pull request for main
        uses: peter-evans/create-pull-request@v6
        if: steps.apply-patch-main.outputs.UPDATE_NEEDED == 1
        with:
          token: ${{ secrets.BOT_PR_TOKEN }}
          path: scripts
          branch: vmware-${{ steps.openvmtools-latest-release.outputs.VERSION_NEW }}-main
          base: main
          title: Upgrade open-vm-tools in main from ${{ steps.apply-patch-main.outputs.VERSION_OLD }} to ${{ steps.openvmtools-latest-release.outputs.VERSION_NEW }}
          body: Subject says it all.
          labels: main
