name: Kotlin
on:
  workflow_call:
  workflow_dispatch:

permissions:
  contents: 'read'
  id-token: 'write'

jobs:
  static-analysis:
    runs-on: ubuntu-22.04
    defaults:
      run:
        working-directory: ./kotlin/android
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 17
      - name: Validate Gradle wrapper
        uses: gradle/wrapper-validation-action@v1
      - name: Setup Gradle
        uses: gradle/gradle-build-action@v2
        with:
          cache-read-only: ${{ github.ref != 'refs/heads/main' }}
          build-root-directory: ./kotlin/android
      - run: touch local.properties
      - name: Run linter
        run: ./gradlew spotlessCheck

  build:
    runs-on: ubuntu-22.04
    defaults:
      run:
        working-directory: ./kotlin/android
    steps:
      - uses: actions/checkout@v4
      - uses: ./.github/actions/setup-rust
        with:
          targets: armv7-linux-androideabi aarch64-linux-android x86_64-linux-android i686-linux-android
      - uses: actions/setup-java@v4
        with:
          distribution: oracle
          java-version: 17
      - name: Setup Gradle
        uses: gradle/gradle-build-action@v2
        with:
          cache-read-only: ${{ github.ref != 'refs/heads/main' }}
          build-root-directory: ./kotlin/android
          # https://github.com/gradle/gradle-build-action#overwriting-an-existing-gradle-user-home
          cache-overwrite-existing: ${{ github.ref == 'refs/heads/main' }}
      - run: touch local.properties
      - name: Bundle and sign release
        env:
          KEYSTORE_BASE64: ${{ secrets.GOOGLE_UPLOAD_KEYSTORE_BASE64 }}
          KEYSTORE_PASSWORD: ${{ secrets.GOOGLE_UPLOAD_KEYSTORE_PASSWORD }}
          KEYSTORE_KEY_PASSWORD: ${{ secrets.GOOGLE_UPLOAD_KEYSTORE_KEY_PASSWORD }}
        run: |
          KEYSTORE_PATH=$(pwd)/app/keystore.jks
          echo -n "$KEYSTORE_BASE64" | base64 --decode > $KEYSTORE_PATH
          ./gradlew --info bundleRelease
      - name: Run Test
        run: |
          # TODO: See https://github.com/firezone/firezone/issues/2311
          # TODO: See https://github.com/firezone/firezone/issues/2309
          ./gradlew testReleaseUnitTest
      - name: Android Test Report
        uses: asadmansr/android-test-report-action@v1.2.0
        if: "!cancelled()"
      - name: Upload release
        if: ${{ github.event_name == 'workflow_dispatch' || (github.ref == 'refs/heads/main' && contains(github.event.head_commit.modified, 'elixir/VERSION')) }}
        env:
          FIREBASE_APP_DISTRIBUTION_CREDENTIALS: ${{ secrets.FIREBASE_APP_DISTRIBUTION_CREDENTIALS }}
          FIREBASE_CREDENTIALS_PATH: firebase-credentials.json
          FIREBASE_APP_TESTERS: ${{ vars.FIREBASE_APP_TESTERS }}
        run: |
          echo -n "$FIREBASE_APP_DISTRIBUTION_CREDENTIALS" > $FIREBASE_CREDENTIALS_PATH
          ./gradlew --info appDistributionUploadRelease
