# SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors
# SPDX-FileCopyrightText: 2023 Andy Scherzinger <info@andy-scherzinger.de>
# SPDX-License-Identifier: MIT
name: "QA"

on:
  pull_request:
    branches: [ main, master, stable-* ]

permissions:
  pull-requests: write
  contents: read

concurrency:
  group: qa-build-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

jobs:
  qa:
    runs-on: ubuntu-latest
    steps:
      - name: Check if secrets are available
        run: echo "ok=${{ secrets.KS_PASS != '' }}" >> "$GITHUB_OUTPUT"
        id: check-secrets

      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        if: ${{ steps.check-secrets.outputs.ok == 'true' }}
        with:
          persist-credentials: false

      - name: set up JDK 17
        uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
        if: ${{ steps.check-secrets.outputs.ok == 'true' }}
        with:
          distribution: "temurin"
          java-version: 17

      - name: Build QA
        if: ${{ steps.check-secrets.outputs.ok == 'true' }}
        env:
          KS_PASS: ${{ secrets.KS_PASS }}
          KEY_PASS: ${{ secrets.KEY_PASS }}
          LOG_USERNAME: ${{ secrets.LOG_USERNAME }}
          LOG_PASSWORD: ${{ secrets.LOG_PASSWORD }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          mkdir -p "$HOME/.gradle"
          echo "org.gradle.jvmargs=-Xmx3g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=1g" > "$HOME/.gradle/gradle.properties"
          echo "org.gradle.caching=true; org.gradle.parallel=true; org.gradle.configureondemand=true; kapt.incremental.apt=true" >> "$HOME/.gradle/gradle.properties"
          [ -e app/build.gradle ] && sed -i "/qa/,/\}/ s/versionCode .*/versionCode ${{github.event.number}} /" "app/build.gradle"
          [ -e app/build.gradle ] && sed -i "/qa/,/\}/ s/versionName .*/versionName \"${{github.event.number}}\"/" "app/build.gradle"
          [ -e app/build.gradle.kts ] && sed -i "/qa/,/\}/ s/versionCode .*/versionCode = ${{github.event.number}} /" "app/build.gradle.kts"
          [ -e app/build.gradle.kts ] && sed -i "/qa/,/\}/ s/versionName .*/versionName = \"${{github.event.number}}\"/" "app/build.gradle.kts"
          ./gradlew assembleQaDebug
          $(find /usr/local/lib/android/sdk/build-tools/*/apksigner | sort | tail -n1) sign  --ks-pass pass:"$KS_PASS" --key-pass pass:"$KEY_PASS" --ks-key-alias key0 --ks ".github/workflows/QA_keystore.jks" app/build/outputs/apk/qa/debug/*qa-debug*.apk
          .github/workflows/uploadArtifact.sh "$LOG_USERNAME" "$LOG_PASSWORD" "${{github.event.number}}" "${{github.event.number}}" "$GITHUB_TOKEN"
