name: Build sing-box rule-set (srs)

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: 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 singbox rule-set
      run: python build_singbox.py
      working-directory: ./script/

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

        git add ./rule/singbox

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

        git commit -m "Update singbox 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
