name: Manager

on:
  push:
    branches: [ master ]
    paths:
    - 'app/**'
    - '.github/workflows/manager.yml'
  pull_request:
    paths:
    - 'app/**'

jobs:
  build:
    runs-on: ubuntu-latest
    if: ${{ !startsWith(github.event.head_commit.message, '[skip ci]') }}

    steps:
      - uses: actions/checkout@v2
        with:
          submodules: 'recursive'
      - name: set up JDK 1.8
        uses: actions/setup-java@v1
        with:
          java-version: 1.8
      - name: Get version code
        run: echo APPVEYOR_BUILD_NUMBER=$(expr $GITHUB_RUN_NUMBER + 4999) >> $GITHUB_ENV
      - name: Build with Gradle
        run:  bash ./gradlew :app:assembleRelease
      - name: Sign Manager Release
        if: ${{ github.event_name != 'pull_request' && success() && github.ref == 'refs/heads/master' }}
        id: sign
        uses: LSPosed/sign-android-release@v1.0.0
        with:
          releaseDirectory: app/build/outputs/apk/release
          signingKeyBase64: ${{ secrets.SIGNING_KEY }}
          alias: ${{ secrets.ALIAS }}
          keyStorePassword: ${{ secrets.KEY_STORE_PASSWORD }}
          keyPassword: ${{ secrets.KEY_PASSWORD }}
        env:
          BUILD_TOOLS_VERSION: "30.0.3"
      - name: Upload signed apk
        if: ${{ github.event_name != 'pull_request' && success() && github.ref == 'refs/heads/master' }}
        uses: actions/upload-artifact@v2
        with:
          name: manager
          path: ${{ steps.sign.outputs.signedReleaseFile }}
      - name: Upload unsigned apk
        if: ${{ github.event_name == 'pull_request' || failure() }}
        uses: actions/upload-artifact@v2
        with:
          name: manager-unsigned
          path: "app/build/outputs/apk/release/*.apk"
      - name: Upload mappings
        uses: actions/upload-artifact@v2
        with:
          name: mappings
          path: "app/build/outputs/mapping"
      - name: Post to channel
        if: ${{ github.event_name != 'pull_request' && success() && github.ref == 'refs/heads/master' }}
        env:
          CHANNEL_ID: ${{ secrets.CHANNEL_ID }}
          BOT_TOKEN: ${{ secrets.BOT_TOKEN }}
          FILE: ${{ steps.sign.outputs.signedReleaseFile }}
          COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
        run: |
          ESCAPED=`python3 -c 'import json,os,urllib.parse; print(urllib.parse.quote(json.dumps(os.environ["COMMIT_MESSAGE"])))'`
          curl -v "https://api.telegram.org/bot${BOT_TOKEN}/sendMediaGroup?chat_id=${CHANNEL_ID}&media=%5B%7B%22type%22:%22document%22,%20%22media%22:%22attach://release%22,%22caption%22:${ESCAPED}%7D%5D"  -F release="@$FILE"
