name: Build SU
on:
  push:
    branches: [ "main" ]
    paths: 
      - '.github/workflows/build-su.yml'
      - 'userspace/su/**'
      - 'scripts/ksubot.py'
  pull_request:
    branches: [ "main" ]
    paths: 
      - 'userspace/su/**'
jobs:
  build-su:
    name: Build userspace su
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
      with:
        fetch-depth: 0
    - name: Setup need_upload
      id: need_upload
      run: |
        if [ ! -z "${{ secrets.BOT_TOKEN }}" ]; then
          echo "UPLOAD=true" >> $GITHUB_OUTPUT
        else
          echo "UPLOAD=false" >> $GITHUB_OUTPUT
        fi
    - uses: nttld/setup-ndk@v1
      with:
        ndk-version: r25b
        local-cache: true
    - name: Build su
      working-directory: ./userspace/su
      run: ndk-build
    - name: Upload a Build Artifact
      uses: actions/upload-artifact@v3
      with:
        name: su
        path: ./userspace/su/libs
    - name: Setup mutex for uploading
      uses: ben-z/gh-action-mutex@v1.0-alpha-7
      if: github.event_name != 'pull_request' && steps.need_upload.outputs.UPLOAD == 'true'
    - name: Upload to telegram
      if: github.event_name != 'pull_request' && steps.need_upload.outputs.UPLOAD == 'true'
      env:
        CHAT_ID: ${{ secrets.CHAT_ID }}
        CACHE_CHAT_ID: ${{ secrets.CACHE_CHAT_ID }}
        BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
        MESSAGE_THREAD_ID: ${{ secrets.MESSAGE_THREAD_ID }}
        COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
        COMMIT_URL: ${{ github.event.head_commit.url }}
        RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        TITLE: SU
      run: |
        if [ ! -z "${{ secrets.BOT_TOKEN }}" ]; then
          export VERSION=$(git rev-list --count HEAD)
          pip3 install python-telegram-bot
          mv ./userspace/su/libs/arm64-v8a/su su-arm64
          mv ./userspace/su/libs/x86_64/su su-x86_64
          python3 scripts/ksubot.py su-arm64 su-x86_64
        fi
