name: nvchecker

on:
  push:
    branches:
      - master
  workflow_dispatch:
  schedule:
    # * is a special character in YAML so you have to quote this string
    # UTC 09:00 -> CST (China) 17:00, see https://datetime360.com/cn/utc-cst-china-time/
    - cron: '0 09 * * *'

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  nvchecker:
    if: github.repository == 'microcai/gentoo-zh'
    runs-on: ubuntu-latest
    container:
      image: ghcr.io/liangyongxiang/gentoo-testing:master
    outputs:
      nvcmp: ${{ steps.nvchecker.outputs.nvcmp }}
    steps:
    - name: checkout
      uses: actions/checkout@v4

    - name: gentoo
      run: |
        # eselect
        echo "::group::eselect repository add and sync"
        repo_name=$(cat profiles/repo_name)
        eselect repository add "$repo_name" git "file://${PWD}"
        emerge --sync "$repo_name"
        egencache --jobs=$(nproc) --update --repo "$repo_name" &> /dev/null
        eix-update
        echo "::endgroup::"
        # eix
        echo "::group::eix search packages"
        pkgs=$(ACCEPT_LICENSE="*" ACCEPT_KEYWORDS="~amd64 ~arm64 ~loong ~riscv" EIX_LIMIT=0 NAMEVERSION="<category>/<name>-<version>\n" eix --pure-packages --in-overlay "$repo_name" --format '<bestversion:NAMEVERSION>')
        pkgs=$(qatom -F "\"%{CATEGORY}/%{PN}\": \"%{PV}\"," $pkgs) # remove revision
        echo "$pkgs"
        pkgs="{ ${pkgs::-1} }"
        echo "$pkgs" > .github/workflows/old_ver.json
        # sed -r -i 's/_p[^"]*//' .github/workflows/old_ver.json
        cat .github/workflows/old_ver.json
        echo "::endgroup::"

    - name: nvchecker
      id: nvchecker
      env:
        GITHUB_TOKEN: ${{ secrets.GENTOO_ZH_NVCHECKER_PAT }}
      run: |
        echo "::group::nvchecker"
        cd .github/workflows/
        echo -e "[keys]\ngithub = \"${{ secrets.GITHUB_TOKEN }}\"" > keyfile.toml
        nvchecker --file overlay.toml --keyfile keyfile.toml
        echo "::endgroup::"

        echo "::group::nvcmp"
        echo "nvcmp=$(nvcmp --file overlay.toml --json --newer | jq 'map({name, newver, oldver})' | jq -c .)" >> $GITHUB_OUTPUT
        echo "::endgroup::"

  issues-bumper:
    needs: nvchecker
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include: ${{ fromJson(needs.nvchecker.outputs.nvcmp) }}
    steps:
    - name: Checkout bumpbot
      uses: actions/checkout@v4
      with:
        repository: 'gentoo-zh-drafts/bumpbot'

    - name: Checkout gentoo-zh
      uses: actions/checkout@v4
      with:
        path: 'gentoo-zh'

    - name: update issues
      timeout-minutes: 1
      env:
        name: ${{ matrix.name }}
        newver: ${{ matrix.newver }}
        oldver: ${{ matrix.oldver }}
        GITHUB_TOKEN: ${{ secrets.GENTOO_ZH_NVCHECKER_PAT }} # https://github.com/microcai/gentoo-zh/pull/3130
      run: |
        go run . --file gentoo-zh/.github/workflows/overlay.toml --name "$name" --newver "$newver" --oldver "$oldver"
