name: Compile APK

on:
  workflow_dispatch:

env:
  FLUTTER_VERSION: "3.13.9"
  APK_BUILD_DIR: "/tmp/build"

jobs:
  build:
    runs-on: ubuntu-20.04
    outputs:
      version: ${{ steps.get_version.outputs.version }}

    steps:
      - uses: actions/checkout@v4

      - name: Get version from pubspec.yaml
        id: get_version
        run: |
          VERSION=$(sed -n 's/^version: \([0-9]*\.[0-9]*\.[0-9]*\).*/\1/p' app/pubspec.yaml)
          echo "version=$VERSION" >> $GITHUB_OUTPUT

  build_apk:
    needs: build
    runs-on: ubuntu-22.04

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Remove proprietary dependencies
        run: sh scripts/remove_proprietary_dependencies.sh

      - name: Copy files to env.APK_BUILD_DIR
        run: |
          mkdir -p $APK_BUILD_DIR
          cp -r . $APK_BUILD_DIR

      - name: Decode key.properties file
        working-directory: ${{ env.APK_BUILD_DIR }}
        env:
          ENCODED_STRING: ${{ secrets.ANDROID_KEY_PROPERTIES }}
        run: echo $ENCODED_STRING | base64 -di > app/android/key.properties

      - name: Decode android-keystore.jks file
        working-directory: ${{ env.APK_BUILD_DIR }}
        env:
          ENCODED_STRING: ${{ secrets.ANDROID_KEY_STORE }}
        run: mkdir secrets && echo $ENCODED_STRING | base64 -di > secrets/android-keystore.jks

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

      - name: Install Flutter
        uses: subosito/flutter-action@v2
        with:
          flutter-version: ${{ env.FLUTTER_VERSION }}

      - name: Dependencies
        working-directory: ${{ env.APK_BUILD_DIR }}/app
        run: flutter pub get

      - name: Build APK
        working-directory: ${{ env.APK_BUILD_DIR }}/app
        run: flutter build apk

      - name: Upload APK
        uses: actions/upload-artifact@v3
        with:
          name: apk-result
          path: ${{ env.APK_BUILD_DIR }}/app/build/app/outputs/flutter-apk/app-release.apk
