name: Build and Release APK

on:
  push:
    tags:
      - 'v*' # Triggers on version tags like v1.0, v2.0, etc.
  release:
    types: [created]
  workflow_dispatch: # Allows manual triggering

env:
  main_project_module: app

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'
          cache: 'gradle'

      - name: Grant execute permission for gradlew
        run: chmod +x gradlew

      - name: Decode Keystore
        run: |
          echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 -d > keystore.jks

      - name: Build Release APK
        run: ./gradlew assembleRelease
        env:
          KEYSTORE_FILE: ../keystore.jks
          KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }}
          KEY_ALIAS: ${{ secrets.KEY_ALIAS }}
          KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}

      - name: Get version name
        id: version
        run: |
          echo "VERSION_NAME=$(grep 'versionName' app/build.gradle | awk '{print $3}' | tr -d '\"')" >> $GITHUB_OUTPUT

      - name: Upload Release APK
        uses: actions/upload-artifact@v4
        with:
          name: adbautoenable-${{ steps.version.outputs.VERSION_NAME }}-release
          path: app/build/outputs/apk/release/*.apk

      - name: Create Release and Upload APK
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v1
        with:
          files: app/build/outputs/apk/release/*.apk
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
