name: Make Apk CI

on:
  workflow_dispatch:
  push:
    branches:
      - master
  pull_request:

jobs:
  Build-Apk:
    runs-on: ubuntu-latest
    steps:
    - name: Checkout repo
      uses: actions/checkout@v6
      with:
        submodules: true

    - name: Restore debug keystore from GitHub Secrets
      run: |
        # Check if exist and use the secret named DEBUG_KEYSTORE
        # The contents of the secret can be obtained -
        #  from the debug.keystore.asc from you local folder 
        #  (refer to CONTRIBUTING.md Using the local debug.keystore on the Github CI actions)
        if [[ ! "${{ secrets.DEBUG_KEYSTORE }}" = "" ]]; then
            echo "${{ secrets.DEBUG_KEYSTORE }}" > "debug.keystore.asc"
            if [[ -s "debug.keystore.asc" ]]; then
                echo "Restoring debug keystore from GitHub secrets"
                gpg -d --passphrase "debug0" --batch "debug.keystore.asc" > "debug.keystore"
            fi
        fi

    - uses: actions/setup-java@v4
      with:
        distribution: 'temurin'
        java-version: '17'
    - name: Setup Gradle
      uses: gradle/actions/setup-gradle@v4

    - name: Run tests
      run: |
        gradle test
        # Warn about outdated generated files.
        if ! git diff --name-only; then
          echo "Warning: Generated files are not uptodate. Run 'gradle test'."
        fi

    - name: Build debug APK
      run: ./gradlew assembleDebug
      env:
        DEBUG_KEYSTORE: "debug.keystore"
        DEBUG_KEYSTORE_PASSWORD: debug0
        DEBUG_KEY_ALIAS: debug
        DEBUG_KEY_PASSWORD: debug0

    - name: Artifact naming
      run: |
        artifact="${{github.repository_owner}} ${{github.ref_name}}"
        artifact="${artifact//\//-}" # replace slashes
        echo "artifact=${artifact}" >> $GITHUB_ENV
    - name: Upload debug APK
      uses: actions/upload-artifact@v4
      with:
        name: "${{env.artifact}} debug_apk"
        path: build/outputs/apk/debug/*.apk
