name: Update JDK Version
on:
  schedule:
    - cron:  '0 10 * * *'
  workflow_dispatch:
jobs:
  update-jdk-version:
    runs-on: ubuntu-latest
    env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.x'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install requests

      - name: Check and update JDK version
        run: |
          if [ -f latest_jdk.txt ]; then
            rm latest_jdk.txt  # Remove previous records
          fi
          python .github/scripts/check_and_update_jdk.py
          
      - name: Read latest JDK version from file
        run: |
          if [ -f latest_jdk.txt ]; then
            version=$(cat latest_jdk.txt)
            echo "Latest JDK version: $version"
            echo "latest_jdk=$version" >> $GITHUB_ENV # set the latest_jdk environment variable
          else
            echo "No new JDK version detected, nothing to do"
            exit 0
          fi

      - name: Check for existing PR
        id: check_pr
        run: |
          pr_number=$(gh pr list --search "Found JavaSE version ${{ env.latest_jdk }}" --json number --jq '.[0].number')
          echo "pr_number=$pr_number" >> $GITHUB_ENV

      - name: Branch and push changes
        if: ${{ success() && env.latest_jdk != '' && steps.check_pr.outputs.pr_number == '' }}
        run: |
          git config --global user.email "redhattools-bot@users.noreply.github.com"
          git config --global user.name "redhattools-bot"
          git checkout -b "update-jdk-${{ env.latest_jdk }}"
          git commit -am "Bump JDK to ${{ env.latest_jdk }}"
          git push origin "update-jdk-${{ env.latest_jdk }}"
          gh pr create --title "Found JavaSE version ${{ env.latest_jdk }}" --body "See [Raw logs](https://github.com/${{ github.repository }}/commit/${{ github.sha }}/checks/${{ github.check_run_id }}/logs)"
          
