name: Build mihomo rule-set (mrs)

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

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v2

    - name: "Setup sing-box"
      env:
        SING_BOX_DEB_URL: "https://github.com/SagerNet/sing-box/releases/download/v1.10.0-alpha.27/sing-box_1.10.0-alpha.27_linux_amd64.deb"
      run: |
          set -Eeuo pipefail
          wget -O sing-box.deb $SING_BOX_DEB_URL
          sudo dpkg -i sing-box.deb

    - name: "Setup mihomo"
      run: |
          set -Eeuo pipefail
          MIHOMO_TAG=$(curl -s https://api.github.com/repos/MetaCubeX/mihomo/releases/latest | grep '"tag_name"' | cut -d'"' -f4)
          echo "mihomo 版本: $MIHOMO_TAG"
          wget -O mihomo.gz "https://github.com/MetaCubeX/mihomo/releases/download/${MIHOMO_TAG}/mihomo-linux-amd64-compatible-${MIHOMO_TAG}.gz"
          gzip -d mihomo.gz
          chmod +x mihomo
          sudo mv mihomo /usr/local/bin/mihomo
          mihomo -v

    - name: Set up Python3
      uses: actions/setup-python@v2
      with:
        python-version: 3.x

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

    - name: Build mihomo rule-set
      run: python build_mihomo.py
      working-directory: ./script/

    - name: Commit and push rule/mihomo
      run: |
        git config --global user.email "action@github.com"
        git config --global user.name "GitHub Action"

        git add ./rule/mihomo

        if git diff --staged --quiet; then
          echo "No changes to commit"
          exit 0
        fi

        git commit -m "Update mihomo rule-set"

        for i in 1 2 3 4 5; do
          git fetch origin main
          if git rebase origin/main && git push origin HEAD:main; then
            echo "push 成功"
            exit 0
          fi

          git rebase --abort 2>/dev/null || true
          echo "push 冲突，第 $i 次重试..."
          sleep $(( (RANDOM % 8) + 2 ))
        done

        echo "重试多次仍失败"
        exit 1
