name: Build APK and Upload Artifacts

on:
  push:
    branches:
      - master

jobs:
  build-apk:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v3

      - name: Check commit message
        id: check_commit
        run: |
          COMMIT_MSG=$(git log -1 --pretty=%B)
          echo "Commit message: $COMMIT_MSG"
          if echo "$COMMIT_MSG" | grep -iq "build"; then
            echo "Triggering build"
            echo "BUILD_TRIGGERED=true" >> $GITHUB_ENV
          else
            echo "No 'Build' keyword found, skipping pipeline."
            echo "BUILD_TRIGGERED=false" >> $GITHUB_ENV
          fi

      - name: Set up Java and Android SDK
        if: env.BUILD_TRIGGERED == 'true'
        run: |
          sudo apt-get update -qq && sudo apt-get install -qq -y openjdk-17-jdk wget unzip
          wget https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O android-commandlinetools.zip
          mkdir -p $HOME/Android/Sdk/cmdline-tools
          unzip android-commandlinetools.zip -d $HOME/Android/Sdk/cmdline-tools
          mv $HOME/Android/Sdk/cmdline-tools/cmdline-tools $HOME/Android/Sdk/cmdline-tools/tools
          mkdir -p $HOME/Android/Sdk/licenses
          yes | $HOME/Android/Sdk/cmdline-tools/tools/bin/sdkmanager --licenses || true
          $HOME/Android/Sdk/cmdline-tools/tools/bin/sdkmanager "platforms;android-30" "build-tools;30.0.3" "platforms;android-34" "build-tools;34.0.0"
          
          export ANDROID_HOME=$HOME/Android/Sdk
          echo "ANDROID_HOME=$ANDROID_HOME" >> $GITHUB_ENV

      - name: Set up Gradle
        if: env.BUILD_TRIGGERED == 'true'
        run: |
          sed -i 's/\r$//' gradlew
          chmod +x ./gradlew
          ./gradlew dependencies

      - name: Create or update local.properties
        if: env.BUILD_TRIGGERED == 'true'
        run: |
          echo "sdk.dir=$ANDROID_HOME" > local.properties

      - name: Build APK
        if: env.BUILD_TRIGGERED == 'true'
        run: |
          ./gradlew assembleDebug

      - name: Verify APK existence and non-zero size
        if: env.BUILD_TRIGGERED == 'true'
        run: |
          APK_FILE="app/build/outputs/apk/debug/app-debug.apk"
          if [ ! -f "$APK_FILE" ]; then
            echo "Erreur : L'APK n'a pas été généré !"
            exit 1
          fi
          APK_SIZE=$(stat -c %s "$APK_FILE")
          if [ "$APK_SIZE" -eq 0 ]; then
            echo "Erreur : L'APK est vide !"
            exit 1
          fi
          echo "APK est prêt à être uploadé. Taille : $APK_SIZE octets"

      - name: Upload APK artifact
        if: env.BUILD_TRIGGERED == 'true'
        uses: actions/upload-artifact@v3
        with:
          name: app-debug-apk
          path: app/build/outputs/apk/debug/app-debug.apk
