name: Magisk Build

on:
  push:
    branches: [ master ]
    paths:
      - 'app/**'
      - 'native/**'
      - 'stub/**'
      - 'buildSrc/**'
      - 'build.py'
      - 'gradle.properties'
  pull_request:
    branches: [ master ]
  workflow_dispatch:

jobs:
  build:
    name: Build on ${{ matrix.os }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ ubuntu-latest, windows-latest, macOS-latest ]

    steps:
      - name: Check out
        uses: actions/checkout@v2
        with:
          submodules: 'recursive'
          fetch-depth: 0

      - name: Set up JDK 11
        uses: actions/setup-java@v1
        with:
          java-version: '11'

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

      - name: Set up GitHub env (Windows)
        if: runner.os == 'Windows'
        run: |
          $ndk_ver = Select-String -Path "gradle.properties" -Pattern "^magisk.fullNdkVersion=" | % { $_ -replace ".*=" }
          echo "ANDROID_SDK_ROOT=$env:ANDROID_SDK_ROOT" >> $env:GITHUB_ENV
          echo "MAGISK_NDK_VERSION=$ndk_ver" >> $env:GITHUB_ENV
          echo "GRADLE_OPTS=-Dorg.gradle.daemon=false" >> $env:GITHUB_ENV

      - name: Set up GitHub env (Unix)
        if: runner.os != 'Windows'
        run: |
          ndk_ver=$(sed -n 's/^magisk.fullNdkVersion=//p' gradle.properties)
          echo ANDROID_SDK_ROOT=$ANDROID_SDK_ROOT >> $GITHUB_ENV
          echo MAGISK_NDK_VERSION=$ndk_ver >> $GITHUB_ENV

      - name: Cache Gradle
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle.kts') }}
          restore-keys: ${{ runner.os }}-gradle-

      - name: Cache NDK
        id: ndk-cache
        uses: actions/cache@v2
        with:
          path: ${{ env.ANDROID_SDK_ROOT }}/ndk/magisk
          key: ${{ runner.os }}-ndk-${{ env.MAGISK_NDK_VERSION }}

      - name: Set up NDK
        if: steps.ndk-cache.outputs.cache-hit != 'true'
        run: python build.py ndk

      - name: Build release
        run: python build.py -vr all

      - name: Refresh flag
        run: touch gradle.properties
        shell: bash

      - name: Build debug
        run: python build.py -v all

      # Only upload artifacts built on Linux
      - name: Upload build artifact
        if: runner.os == 'Linux'
        uses: actions/upload-artifact@v2
        with:
          name: ${{ github.sha }}
          path: out
