name: Check Kernel 6.18 Release

on:
  schedule:
    - cron: '0 3 * * *'
  workflow_dispatch:

jobs:
  check-kernel:
    if: github.repository == 'kernelkit/infix'
    runs-on: ubuntu-latest

    steps:
      - name: Check out infix repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.KERNEL_UPDATE_TOKEN }}

      - name: Fetch kernel.org and check for 6.18 release
        id: check
        run: |
          set -e -o pipefail
          # Fetch the kernel.org frontpage and extract 6.18 version
          CURRENT_VERSION=$(curl -s https://www.kernel.org/ | grep -oP '6\.18\.\d+' | head -n1)

          if [ -z "$CURRENT_VERSION" ]; then
            echo "Failed to fetch kernel version"
            exit 1
          fi

          echo "current_version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
          echo "Current 6.18 kernel version: $CURRENT_VERSION"

          # Get the version from infix defconfig
          INFIX_VERSION=$(grep 'BR2_LINUX_KERNEL_CUSTOM_VERSION_VALUE=' configs/aarch64_defconfig | cut -d'"' -f2)

          echo "infix_version=$INFIX_VERSION" >> $GITHUB_OUTPUT
          echo "Infix kernel version: $INFIX_VERSION"

          if [ "$CURRENT_VERSION" != "$INFIX_VERSION" ]; then
            # Check if there's already an open PR for this version
            PR_EXISTS=$(gh pr list --state open --search "Upgrade to kernel $CURRENT_VERSION in:title" --json number --jq 'length')

            if [ "$PR_EXISTS" -gt 0 ]; then
              echo "new_release=false" >> $GITHUB_OUTPUT
              echo "PR already exists for kernel $CURRENT_VERSION, skipping"
            else
              echo "new_release=true" >> $GITHUB_OUTPUT
              echo "🎉 New 6.18 kernel released: $CURRENT_VERSION (infix version: $INFIX_VERSION)"
            fi
          else
            echo "new_release=false" >> $GITHUB_OUTPUT
            echo "No change - still at $CURRENT_VERSION"
          fi
        env:
          GH_TOKEN: ${{ secrets.KERNEL_UPDATE_TOKEN }}

      - name: Generate branch name
        if: steps.check.outputs.new_release == 'true'
        id: branch
        run: |
          BRANCH_NAME="kernel-upgrade-$(uuidgen | tr '[:upper:]' '[:lower:]')"
          echo "name=$BRANCH_NAME" >> $GITHUB_OUTPUT
          echo "Branch name: $BRANCH_NAME"

      - name: Import GPG key
        if: steps.check.outputs.new_release == 'true'
        run: |
          # Import the GPG key
          echo "${{ secrets.AEL_BOT_GPG_PRIVATE_KEY }}" | gpg --batch --import

          # Get the key ID
          GPG_KEY_ID=$(gpg --list-secret-keys --keyid-format=long | grep '^sec' | head -1 | awk '{print $2}' | cut -d'/' -f2)
          echo "GPG_KEY_ID=$GPG_KEY_ID" >> $GITHUB_ENV

          # Configure GPG agent for non-interactive use
          echo "allow-loopback-pinentry" >> ~/.gnupg/gpg-agent.conf
          echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf
          gpg-connect-agent reloadagent /bye || true

      - name: Set up git credentials
        if: steps.check.outputs.new_release == 'true'
        run: |
          set -e -o pipefail
          git config --global user.email "ael-bot@users.noreply.github.com"
          git config --global user.name "ael-bot"
          git config --global commit.gpgsign true
          git config --global user.signingkey ${{ env.GPG_KEY_ID }}

          # Configure git to use the token for HTTPS operations
          git config --global url."https://ael-bot:${{ secrets.KERNEL_UPDATE_TOKEN }}@github.com/".insteadOf "git@github.com:"
          git config --global url."https://ael-bot:${{ secrets.KERNEL_UPDATE_TOKEN }}@github.com/".insteadOf "https://github.com/"

      - name: Run kernel upgrade script
        if: steps.check.outputs.new_release == 'true'
        env:
          GIT_TERMINAL_PROMPT: 0
          BRANCH_NAME: ${{ steps.branch.outputs.name }}
        run: |
          set -e -o pipefail
          ./utils/kernel-upgrade.sh linux 6.18 "$BRANCH_NAME"

      - name: Create pull request
        if: steps.check.outputs.new_release == 'true'
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.KERNEL_UPDATE_TOKEN }}
          script: |
            const { data: pulls } = await github.rest.pulls.list({
              owner: context.repo.owner,
              repo: context.repo.repo,
              head: `${context.repo.owner}:kernel-upgrade`,
              state: 'open'
            });

            if (pulls.length === 0) {
              const { data: pr } = await github.rest.pulls.create({
                owner: context.repo.owner,
                repo: context.repo.repo,
                title: `Upgrade to kernel ${{ steps.check.outputs.current_version }}`,
                head: '${{ steps.branch.outputs.name }}',
                base: 'main',
                body: `Automated kernel upgrade to version ${{ steps.check.outputs.current_version }}.\n\n**Previous version:** ${{ steps.check.outputs.infix_version }}\n**New version:** ${{ steps.check.outputs.current_version }}\n**Source:** https://www.kernel.org/\n\nThis PR was automatically created by the kernel release monitoring workflow.`
              });

              await github.rest.issues.addLabels({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pr.number,
                labels: ['ci:main']
              });

              await github.rest.pulls.requestReviewers({
                owner: context.repo.owner,
                repo: context.repo.repo,
                pull_number: pr.number,
                reviewers: ['troglobit', 'wkz', 'mattiaswal']
              });
            }
