---
name: Kubernetes-Auto-Support

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

jobs:
  update-kubernetes-version:
    runs-on: ubuntu-latest
    if: github.repository == 'kubesphere/kubekey'
    steps:
      - uses: actions/checkout@v4

      - name: install dependiencies
        run: |
          sudo apt update
          pip install natsort
          
          wget https://attack-on-titan.gd2.qingstor.com/qsctl/v2.4.3/qsctl_v2.4.3_linux_amd64.tar.gz
          tar -zxvf qsctl_v2.4.3_linux_amd64.tar.gz
          mv qsctl_v2.4.3_linux_amd64 /usr/local/bin/qsctl
          rm -rf qsctl_v2.4.3_linux_amd64.tar.gz
          
          VERSION="1.2.2"
          curl -LO "https://github.com/oras-project/oras/releases/download/v${VERSION}/oras_${VERSION}_linux_amd64.tar.gz"
          mkdir -p oras-install/
          tar -zxf oras_${VERSION}_*.tar.gz -C oras-install/
          sudo mv oras-install/oras /usr/local/bin/
          rm -rf oras_${VERSION}_*.tar.gz oras-install/

      - name: update components.json
        id: get_new_version
        run: |
          chmod +x hack/auto-update-version.py
          hack/auto-update-version.py
          [ -f version.tmp ] && echo "UPDATE_VERSION=true" >> $GITHUB_OUTPUT || :

      - name: sync kubernetes
        id: sync_kubernetes
        run: |
          for v in $(cat version.tmp)
          do
            KUBERNETES_VERSION=$v QSCTL_ACCESS_KEY_ID=${{ secrets.QSCTL_ACCESS_KEY_ID }} QSCTL_SECRET_ACCESS_KEY=${{secrets.QSCTL_SECRET_ACCESS_KEY}} DOCKERHUB_USERNAME=${{ secrets.DOCKERHUB_USERNAME }} DOCKERHUB_PASSWORD=${{ secrets.DOCKERHUB_PASSWORD }} ALIYUNCS_USERNAME=${{ secrets.ALIYUNCS_USERNAME }} ALIYUNCS_PASSWORD=${{ secrets.ALIYUNCS_PASSWORD }} bash hack/sync-components.sh
          done
          echo "NEW_VERSION=`cat version.tmp | tr '\n' ', '`" >> $GITHUB_OUTPUT
          rm -rf qsctl-config.yaml
          rm -rf version.tmp
          
          make kk
          chmod +x bin/kk
          echo "## Kubernetes Versions(amd64/arm64)" > docs/kubernetes-versions.md
          echo "| Version  | Supported          |" >> docs/kubernetes-versions.md
          echo "|----------|--------------------|" >> docs/kubernetes-versions.md
          bin/kk version --show-supported-k8s | ( while read version; do echo "| $version | :white_check_mark: |" >> docs/kubernetes-versions.md; done )

        if: steps.get_new_version.outputs.UPDATE_VERSION == 'true'

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v6
        with:
          commit-message: Add new kubernetes version
          committer: GitHub <noreply@github.com>
          signoff: false
          branch: new_version
          delete-branch: true
          title: 'Add new kubernetes version'
          body: |
            Add kubernetes version: ${{ steps.sync_kubernetes.outputs.NEW_VERSION }}

        if: steps.get_new_version.outputs.UPDATE_VERSION == 'true'
