name: main

on:
  workflow_dispatch:
  push:
    branches: [ main ]
    paths-ignore:
      - '**.md'
      - '**.txt'
      - '.github/**'
      - '.idea/**'
      - '!.github/workflows/**'

jobs:
  build:
    name: Build CI (Push)
    runs-on: ubuntu-latest
    if: ${{ !startsWith(github.event.head_commit.message, '[skip ci]') }} && success() && github.ref == 'refs/heads/main' }}

    steps:
      - uses: actions/checkout@v2
        with:
          submodules: 'recursive'
          fetch-depth: 0
      - name: set up JDK 17
        uses: actions/setup-java@v2
        with:
          java-version: '17'
          distribution: 'adopt'
      - name: Setup cmake
        run: |
          echo "y" | sudo ${ANDROID_HOME}/tools/bin/sdkmanager --install "cmake;3.22.1" --sdk_root=${ANDROID_SDK_ROOT} &> /dev/null
          echo "sdk.dir=${ANDROID_HOME}" > local.properties
      - name: Install ccache
        run: |
          sudo apt install -y ccache
          ccache -o max_size=1G
          ccache -o hash_dir=false
          ccache -o hard_link=true
          ccache -o compiler_check='%compiler% -dumpmachine; %compiler% -dumpversion'
          ccache -zp
      - name: Cache Native Build
        uses: actions/cache@v2
        with:
          path: |
            ~/.cache/ccache
            ~/.ccache
            app/build/.lto-cache
          key: native-cache-${{ github.sha }}
          restore-keys: native-cache-
      - name: Cache Gradle Dependencies
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
            !~/.gradle/caches/build-cache-*
          key: gradle-deps-core-${{ hashFiles('**/build.gradle.kts') }}
          restore-keys: |
            gradle-deps
      - name: Cache Gradle Build
        uses: actions/cache@v2
        with:
          path: |
            ~/.gradle/caches/build-cache-*
            ~/.gradle/buildOutputCleanup/cache.properties
          key: gradle-builds-core-${{ github.sha }}
          restore-keys: |
            gradle-builds
      - name: Grant execute permission for gradlew
        run: chmod +x gradlew

      - name: Build with Gradle
        run: |
          [ $(du -s ~/.gradle/wrapper | awk '{ print $1 }') -gt 250000 ] && rm -rf ~/.gradle/wrapper/* || true
          find ~/.gradle/caches -exec touch -d "2 days ago" {} + || true
          echo 'org.gradle.caching=true' >> gradle.properties
          echo 'org.gradle.parallel=true' >> gradle.properties
          echo 'org.gradle.vfs.watch=true' >> gradle.properties
          echo 'buildCache { local { removeUnusedEntriesAfterDays = 1 } }' >> settings.gradle.kts
          echo ${{ secrets.SIGN_KEYSTORE_BASE64 }} | base64 -d > keystore.jks
          ./gradlew :app:synthesizeDistReleaseApksCI
          ccache -s
          echo "APK_FILE_ARM32=$(find app/build/outputs/ci -name '*arm32.apk')" >> $GITHUB_ENV
          echo "APK_FILE_ARM64=$(find app/build/outputs/ci -name '*arm64.apk')" >> $GITHUB_ENV
          echo "APK_FILE_ARMALL=$(find app/build/outputs/ci -name '*armAll.apk')" >> $GITHUB_ENV
          echo "APK_FILE_UNIVERSAL=$(find app/build/outputs/ci -name '*universal.apk')" >> $GITHUB_ENV
        env:
          KEYSTORE_PATH: "../keystore.jks"
          KEYSTORE_PASSWORD: ${{ secrets.SIGN_KEYSTORE_PASSWORD }}
          KEY_ALIAS: ${{ secrets.SIGN_ALIAS }}
          KEY_PASSWORD: ${{ secrets.SIGN_KEY_PASSWORD }}

      - name: Show Artifacts MD5
        run: |
          echo "### Build Success :rocket:" >> $GITHUB_STEP_SUMMARY
          echo "|ABI|MD5|" >> $GITHUB_STEP_SUMMARY
          echo "|:--------:|:----------|" >> $GITHUB_STEP_SUMMARY
          arm32=($(md5sum ${{ env.APK_FILE_ARM32 }}))
          echo "|arm32|$arm32" >> $GITHUB_STEP_SUMMARY
          arm64=($(md5sum ${{ env.APK_FILE_ARM64 }}))
          echo "|arm64|$arm64" >> $GITHUB_STEP_SUMMARY
          armAll=($(md5sum ${{ env.APK_FILE_ARMALL }}))
          echo "|armAll|$armAll" >> $GITHUB_STEP_SUMMARY
          universal=($(md5sum ${{ env.APK_FILE_UNIVERSAL }}))
          echo "|universal|$universal" >> $GITHUB_STEP_SUMMARY

      - name: Upload Artifacts(arm32)
        uses: actions/upload-artifact@v2
        with:
          path: ${{ env.APK_FILE_ARM32 }}
          name: QAuxiliary-release-${{ github.event.head_commit.id }}-arm32
      - name: Upload Artifacts(arm64)
        uses: actions/upload-artifact@v2
        with:
          path: ${{ env.APK_FILE_ARM64 }}
          name: QAuxiliary-release-${{ github.event.head_commit.id }}-arm64
      - name: Upload Artifacts(armAll)
        uses: actions/upload-artifact@v2
        with:
          path: ${{ env.APK_FILE_ARMALL }}
          name: QAuxiliary-release-${{ github.event.head_commit.id }}-armAll
      - name: Upload Artifacts(universal)
        uses: actions/upload-artifact@v2
        with:
          path: ${{ env.APK_FILE_UNIVERSAL }}
          name: QAuxiliary-release-${{ github.event.head_commit.id }}-universal

  upload-telegram:
    name: Upload Release
    if: ${{ success() && github.ref == 'refs/heads/main' }}
    runs-on: ubuntu-latest
    needs:
      - build
      - telegram-bot-api
    steps:
      - name: Donwload Artifacts
        uses: actions/download-artifact@v2
        with:
          path: artifacts
      - name: Download Telegram Bot API Binary
        uses: actions/download-artifact@master
        with:
          name: telegram-bot-api-binary
          path: .
      - name: Release
        env:
          COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
          COMMIT_URL: ${{ github.event.head_commit.url }}
        run: |
          ESCAPED=`python3 -c 'import json,os,urllib.parse; msg = json.dumps(os.environ["COMMIT_MESSAGE"]); print(urllib.parse.quote(msg if len(msg) <= 1024 else json.dumps(os.environ["COMMIT_URL"])))'`
          export arm32=$(find artifacts -name "*arm32.apk")
          export arm64=$(find artifacts -name "*arm64.apk")
          export armAll=$(find artifacts -name "*armAll.apk")
          export universal=$(find artifacts -name "*universal.apk")
          chmod +x telegram-bot-api-binary
          ./telegram-bot-api-binary --api-id=21724 --api-hash=3e0cb5efcd52300aec5994fdfc5bdc16 --local 2>&1 > /dev/null &
          curl -v "http://127.0.0.1:8081/bot${{ secrets.TELEGRAM_TOKEN  }}/sendMediaGroup?chat_id=-1001732413298&media=%5B%7B%22type%22%3A%22document%22%2C%20%22media%22%3A%22attach%3A%2F%2Farm64%22%7D%2C%7B%22type%22%3A%22document%22%2C%20%22media%22%3A%22attach%3A%2F%2Farm32%22%7D%2C%7B%22type%22%3A%22document%22%2C%20%22media%22%3A%22attach%3A%2F%2FarmAll%22%7D%2C%7B%22type%22%3A%22document%22%2C%20%22media%22%3A%22attach%3A%2F%2Funiversal%22%2C%22caption%22:${ESCAPED}%7D%5D" \
           -F arm32="@$arm32" \
           -F arm64="@$arm64" \
           -F armAll="@$armAll" \
           -F universal="@$universal"
          pkill telegram-bot

  upload-taichi:
    name: Upload taichi
    if: ${{ success() && github.ref == 'refs/heads/main' }}
    runs-on: ubuntu-latest
    needs:
      - build
    steps:
      - name: Donwload Artifacts
        uses: actions/download-artifact@v2
        with:
          path: artifacts
      - name: Release
        run: |
          curl "https://gist.githubusercontent.com/qwq233/2a903f28a38d48d57731a1e4d6358948/raw/80e515d659a6f3c4737a1674f50fae5087e1f83c/taichi.py" -o taichi.py
          sudo apt install -y python3-pip
          pip3 install requests
          echo ${{ secrets.TC_UPLOAD_USER_TOKEN }} | base64 -d > taichi.json
          export release=$(find $OUTPUT -name "*armAll.apk")
          python3 taichi.py $release

  telegram-bot-api:
    name: Telegram Bot API
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Clone Telegram Bot API
        run: |
          git clone --recursive https://github.com/tdlib/telegram-bot-api.git
          git status telegram-bot-api >> telegram-bot-api-status
      - name: Cache Bot API Binary
        id: cache-bot-api
        uses: actions/cache@v2
        with:
          path: telegram-bot-api-binary
          key: CI-telegram-bot-api-${{ hashFiles('telegram-bot-api-status') }}
      - name: Compile Telegram Bot API
        if: steps.cache-bot-api.outputs.cache-hit != 'true'
        run: |
          sudo apt-get update
          sudo apt-get install make git zlib1g-dev libssl-dev gperf cmake g++
          cd telegram-bot-api
          rm -rf build
          mkdir build
          cd build
          cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX:PATH=.. ..
          cmake --build . --target install -j$(nproc)
          cd ../..
          ls -l telegram-bot-api/bin/telegram-bot-api*
          cp telegram-bot-api/bin/telegram-bot-api telegram-bot-api-binary
      - name: Upload Binary
        uses: actions/upload-artifact@master
        with:
          name: telegram-bot-api-binary
          path: telegram-bot-api-binary
#  upload-lsp:
#    name: Upload to LSPosed repo
#    if: ${{ github.event_name != 'pull_request' && success() && github.ref == 'refs/heads/main' }}
#    runs-on: ubuntu-latest
#    needs:
#      - build
#    steps:
#      - name: Donwload Artifacts
#        uses: actions/download-artifact@v2
#        id: download
#        with:
#          path: artifacts
#      - name: Generate Changelog
#        env:
#          COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
#          COMMIT_URL: ${{ github.event.head_commit.url }}
#        run: echo "$(python3 -c 'import json,os,urllib.parse; msg = json.dumps(os.environ["COMMIT_MESSAGE"]); print(urllib.parse.quote(msg if len(msg) <= 1024 else json.dumps(os.environ["COMMIT_URL"])))')" > ${{ github.workspace }}-CHANGELOG.txt
#      - name: find apk
#        run: echo "APK_FILE=$(find ${{steps.download.outputs.download-path}} -name '*.apk')" >> $GITHUB_ENV
#      - name: Get Apk Info
#        id: apk
#        uses: JantHsueh/get-apk-info-action@master
#        with:
#          apkPath: ${{ env.APK_FILE }}
#      - name: Get Date
#        id: date
#        run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
#      - name: Release
#        uses: softprops/action-gh-release@v1
#        with:
#          tag_name: ${{steps.apk.outputs.versionCode}}
#          name: CI-${{ steps.date.outputs.date }}
#          body_path: ${{ github.workspace }}-CHANGELOG.txt
#          token: ${{ secrets.PAT_GH_QAUXV_GCS_CI_UPLOAD }}
#          files: ${{ env.APK_FILE }}
#          prerelease: true
#          repository: Xposed-Modules-Repo/io.github.qauxv
#        env:
#          GITHUB_REPOSITORY: Xposed-Modules-Repo/io.github.qauxv
