name: Build and Release Ruleset

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

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      # ── 1. 安装依赖工具 ──────────────────────────────────────────────
      - name: Install jq
        run: sudo apt-get install -y jq

      - name: Install yq
        run: |
          YQ_VER=$(curl -s https://api.github.com/repos/mikefarah/yq/releases/latest | jq -r .tag_name)
          sudo wget -q "https://github.com/mikefarah/yq/releases/download/${YQ_VER}/yq_linux_amd64" -O /usr/local/bin/yq
          sudo chmod +x /usr/local/bin/yq

      - name: Install sing-box
        run: |
          SB_VER=$(curl -s https://api.github.com/repos/SagerNet/sing-box/releases/latest | jq -r .tag_name)
          wget -q "https://github.com/SagerNet/sing-box/releases/download/${SB_VER}/sing-box-${SB_VER#v}-linux-amd64.tar.gz" -O /tmp/sing-box.tar.gz
          tar -xzf /tmp/sing-box.tar.gz -C /tmp
          sudo mv /tmp/sing-box-*/sing-box /usr/local/bin/sing-box

      - name: Install mihomo
        run: |
          MI_VER=$(curl -s https://api.github.com/repos/MetaCubeX/mihomo/releases/latest | jq -r .tag_name)
          wget -q "https://github.com/MetaCubeX/mihomo/releases/download/${MI_VER}/mihomo-linux-amd64-${MI_VER}.gz" -O /tmp/mihomo.gz
          gunzip /tmp/mihomo.gz
          sudo mv /tmp/mihomo /usr/local/bin/mihomo
          sudo chmod +x /usr/local/bin/mihomo

      # ── 2. 构建 sing-box 规则（JSON + SRS）───────────────────────────
      - name: Build sing-box rules
        run: |
          set -e
          BASE="https://raw.githubusercontent.com/evecus/ruleset/refs/heads/master/sing-box"
          mkdir -p /tmp/sing
          cd /tmp/sing

          wget -q "$BASE/cn_ip4-lite.json"
          wget -q "$BASE/cn_ip-lite.json"
          wget -q "$BASE/direct_ip.json"
          wget -q "$BASE/foreign_ip4.json"
          wget -q "$BASE/cn_domain.json"
          wget -q "$BASE/cn_domain-lite.json"
          wget -q "$BASE/direct.json"
          wget -q "$BASE/foreign_domain-lite.json"
          wget -q "$BASE/proxy.json"
          wget -q "$BASE/ads.srs"
          wget https://raw.githubusercontent.com/evecus/ruleset/refs/heads/master/sing-box/foreign_domain.json -O psite-full.json

          merge_json() {
            local output="${@: -1}"
            local inputs=("${@:1:$#-1}")
            jq -s '{
              version: 1,
              rules: [{
                domain:        ([.[].rules[].domain        // []] | flatten | unique | map(select(. != null and . != ""))),
                domain_suffix: ([.[].rules[].domain_suffix // []] | flatten | unique | map(select(. != null and . != ""))),
                ip_cidr:       ([.[].rules[].ip_cidr       // []] | flatten | unique | map(select(. != null and . != "")))
              }]
            } | .rules[0] |= with_entries(select(.value | length > 0))
            ' "${inputs[@]}" > "$output"
          }

          mv foreign_ip4.json    pip.json

          merge_json cn_ip4-lite.json    direct_ip.json dip.json
          merge_json cn_ip-lite.json     direct_ip.json dip6.json
          merge_json cn_domain.json      direct.json    dsite.json
          merge_json cn_domain-lite.json direct.json    dsite-lite.json
          merge_json proxy.json foreign_domain-lite.json psite.json

          rm cn_ip4-lite.json cn_ip-lite.json direct_ip.json
          rm cn_domain.json cn_domain-lite.json direct.json
          rm proxy.json foreign_domain-lite.json

          echo "正在转换 SRS 文件..."
          for file in *.json; do
            output="${file%.json}.srs"
            sing-box rule-set compile "$file" -o "$output"
            echo "成功: $file -> $output"
          done
          echo "sing-box 规则构建完成，共 $(ls | wc -l) 个文件。"

      # ── 3. 构建 mihomo 规则（YAML + MRS）────────────────────────────
      - name: Build mihomo rules
        run: |
          set -e
          BASE="https://raw.githubusercontent.com/evecus/ruleset/refs/heads/master/mihomo"
          mkdir -p /tmp/mi
          cd /tmp/mi

          wget "$BASE/cn_ip4-lite.yaml"
          wget "$BASE/cn_ip-lite.yaml"
          wget "$BASE/direct_ip.yaml"
          wget "$BASE/foreign_ip4.yaml"
          wget "$BASE/cn_domain.yaml"
          wget "$BASE/cn_domain-lite.yaml"
          wget "$BASE/direct.yaml"
          wget "$BASE/foreign_domain-lite.yaml"
          wget "$BASE/proxy.yaml"
          wget "$BASE/ads.yaml"
          wget https://raw.githubusercontent.com/evecus/ruleset/refs/heads/master/mihomo/foreign_domain.yaml -O psite-full.yaml

          merge_yaml() {
            local output="${@: -1}"
            local inputs=("${@:1:$#-1}")
            yq ea '.payload = ([.payload[]] | unique | sort) | select(fi == 0)' "${inputs[@]}" > "$output"
          }

          mv foreign_ip4.yaml    pip.yaml

          merge_yaml cn_ip4-lite.yaml    direct_ip.yaml dip.yaml
          merge_yaml cn_ip-lite.yaml     direct_ip.yaml dip6.yaml
          merge_yaml cn_domain.yaml      direct.yaml    dsite.yaml
          merge_yaml cn_domain-lite.yaml direct.yaml    dsite-lite.yaml
          merge_yaml proxy.yaml foreign_domain-lite.yaml psite.yaml

          rm cn_ip4-lite.yaml cn_ip-lite.yaml direct_ip.yaml
          rm cn_domain.yaml cn_domain-lite.yaml direct.yaml
          rm proxy.yaml foreign_domain-lite.yaml

          echo "开始批量转换 YAML 为 MRS..."
          for file in *.yaml; do
            [ -e "$file" ] || continue
            filename="${file%.yaml}"
            output="${filename}.mrs"
            if [[ "$filename" =~ [Ii][Pp] ]]; then
              mihomo convert-ruleset ipcidr yaml "$file" "$output"
            else
              mihomo convert-ruleset domain yaml "$file" "$output"
            fi
            echo "成功: $file -> $output"
          done
          echo "mihomo 规则构建完成，共 $(ls | wc -l) 个文件。"

      # ── 4. 检出 release 分支并推送 ───────────────────────────────────
      - name: Checkout or create release branch
        run: |
          git config --global user.name  "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git clone --depth=1 --branch=release \
            "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" \
            repo 2>/dev/null || {
            git clone --depth=1 \
              "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" \
              repo
            cd repo
            git checkout --orphan release
            git rm -rf . --quiet || true
            git commit --allow-empty -m "init: release branch"
            git push origin release
            cd ..
          }

      - name: Copy built files
        run: |
          mkdir -p repo/sing-box repo/mihomo
          cp /tmp/sing/*.json repo/sing-box/
          cp /tmp/sing/*.srs  repo/sing-box/
          cp /tmp/mi/*.yaml   repo/mihomo/
          cp /tmp/mi/*.mrs    repo/mihomo/

      - name: Commit and push
        working-directory: repo
        run: |
          git add sing-box/ mihomo/
          if git diff --cached --quiet; then
            echo "规则集无变化，跳过提交。"
          else
            git commit -m "chore: update ruleset $(date -u '+%Y-%m-%d %H:%M UTC')"
            git push origin release
          fi
