name: Publish on Github

on:
  workflow_dispatch: {}
  push:
    branches:
      - main
    paths:
      - pubspec.yaml

jobs:
  build_and_publish:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Clone repository
        uses: actions/checkout@v4

      - name: Set up Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: stable

      - name: Cloning sub-repos
        run: git submodule update --init --recursive

      # - name: Check flutter code
      #   run: | 
      #     flutter pub get
      #     flutter analyze
      #     flutter test

      - name: Check flutter code
        run: flutter pub get

      - name: Create key.properties file
        run: |
          echo "storePassword=${{ secrets.STORE_PASSWORD }}" >> ./android/key.properties
          echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> ./android/key.properties
          echo "keyAlias=github-releases-signature" >> ./android/key.properties
          echo "storeFile=./keystore.jks" >> ./android/key.properties

      - name: Create keystore file
        env:
          KEYSTORE_FILE: ${{ secrets.KEYSTORE_FILE }}
        run: echo $KEYSTORE_FILE | base64 --decode > ./android/app/keystore.jks

      - name: Build Android APK
        run: flutter build apk --release --split-per-abi

      - name: Extract pubspec version
        run: |
          echo "PUBSPEC_VERSION=$(grep -oP 'version:\s*\K[^+]+(?=\+)' pubspec.yaml)" >> $GITHUB_ENV

      - name: Upload Release Binaries (stable)
        uses: ncipollo/release-action@v1.18.0
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          tag: v${{ env.PUBSPEC_VERSION }}
          allowUpdates: true
          artifacts: build/app/outputs/flutter-apk/*.apk