name: mihomo_mrs文件生成

on:
  workflow_dispatch:

permissions:
  contents: write

jobs:
  convert:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout master branch
        uses: actions/checkout@v4
        with:
          ref: master
          # 删掉了 sparse-checkout 相关的配置，确保整个仓库可见

      - name: Install mihomo
        run: |
          # 确保下载的是正确的版本
          wget https://github.com/MetaCubeX/mihomo/releases/download/v1.19.17/mihomo-linux-amd64-v1.19.17.gz
          gunzip mihomo-linux-amd64-v1.19.17.gz
          mv mihomo-linux-amd64-v1.19.17 mihomo_bin
          chmod +x mihomo_bin
          sudo mv mihomo_bin /usr/local/bin/mihomo

      - name: Convert YAML to MRS
        run: |
          # 先确认 mihomo 文件夹到底在哪
          echo "当前工作目录内容："
          ls -R
          
          # 如果你的 yaml 文件就在仓库根目录的 mihomo 文件夹里：
          if [ ! -d "mihomo" ]; then
            echo "错误：仓库中不存在 mihomo 文件夹！"
            exit 1
          fi

          find mihomo -type f -name "*.yaml" | while read -r FILE; do
            OUTPUT="${FILE%.yaml}.mrs"
            echo "正在处理: $FILE"
            # 尝试 domain 格式
            if ! mihomo convert-ruleset domain yaml "$FILE" "$OUTPUT" 2>/dev/null; then
                # 失败则尝试 ipcidr 格式
                if ! mihomo convert-ruleset ipcidr yaml "$FILE" "$OUTPUT" 2>/dev/null; then
                    echo "跳过 (格式不匹配): $FILE"
                fi
            fi
          done

      - name: Commit and push
        run: |
          git config --global user.name "GitHub Action"
          git config --global user.email "actions@github.com"
          
          # 强制添加所有生成的 mrs 文件
          git add mihomo/*.mrs
          
          if git diff --staged --quiet; then
            echo "没有文件变动"
          else
            git commit -m "Auto convert Mihomo rules"
            git push origin master
          fi
