name: Android CI

on: [push, pull_request, workflow_dispatch]

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
      with:
        submodules: recursive

    - name: Setup Java JDK
      uses: actions/setup-java@v4.2.1
      with:
        distribution: 'temurin'
        java-version: '21'

    - name: setup android development environment
      uses: android-actions/setup-android@v2

    - name: install dependencies
      run: |
        npm install -g pnpm

    - name: Update Submodules
      run: |
        git submodule foreach --recursive 'git pull --rebase origin main --allow-unrelated-histories'
      continue-on-error: true

    - name: Pull Assets
      run: |
        git clone https://${{ secrets.ACCESS_TOKEN_GITHUB }}@github.com/imas-tools/gakumas-raw-txts.git app/src/main/assets/gakumas-local/gakumas-raw-txts
        mv app/src/main/assets/gakumas-local/gakumas-raw-txts/Resource app/src/main/assets/gakumas-local/raw
        rm -rf app/src/main/assets/gakumas-local/gakumas-raw-txts
      continue-on-error: true

    - name: Build Assets
      run: |
        mv app/src/main/assets/gakumas-local/GakumasPreTranslation/.env.sample app/src/main/assets/gakumas-local/GakumasPreTranslation/.env
        cd app/src/main/assets/gakumas-local && make build-resource
      continue-on-error: true

    - name: Write branch and commit info
      run: |
        branch=$(git rev-parse --abbrev-ref HEAD)
        hash=$(git rev-parse --short=8 HEAD)
        echo "$branch.$hash" > app/src/main/assets/gakumas-local/version.txt
              
    - name: Grant execute permission for gradlew
      run: chmod +x gradlew

    - name: Build with Gradle
      run: ./gradlew build

    - uses: actions/upload-artifact@v4
      with:
        name: GakumasLocalify-Unsigned-apk
        path: app/build/outputs/apk/debug/app-debug.apk

    - name: Upload Unsigned APK with v3 if v4 failed
      if: failure()
      uses: actions/upload-artifact@v3
      with:
        name: GakumasLocalify-Unsigned-apk
        path: app/build/outputs/apk/debug/app-debug.apk

    - uses: ilharp/sign-android-release@v1
      name: Sign app APK
      id: sign_app
      with:
        releaseDir: app/build/outputs/apk/debug
        signingKey: ${{ secrets.KEYSTOREB64 }}
        keyAlias: ${{ secrets.ANDROID_KEY_ALIAS }}
        keyStorePassword: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
        keyPassword: ${{ secrets.ANDROID_KEY_PASSWORD }}
        buildToolsVersion: 33.0.0
      continue-on-error: true

    - uses: actions/upload-artifact@v4
      with:
        name: GakumasLocalify-Signed-apk
        path: ${{steps.sign_app.outputs.signedFile}}

    - name: Upload Signed APK with v3 if v4 failed
      if: failure()
      uses: actions/upload-artifact@v3
      with:
        name: GakumasLocalify-Signed-apk
        path: ${{steps.sign_app.outputs.signedFile}}
      continue-on-error: true
