name: build-flutter-release

on:
  push:
    tags: ['v*']

jobs:
  build-apk:
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3

      - name: Get subtracks version
        run: echo "SUBTRACKS_VERSION=$(yq '.version' pubspec.yaml | cut -d '+' -f 1)" >> $GITHUB_ENV

      - uses: subosito/flutter-action@v2
        with:
          flutter-version: '3.7.11'
          channel: 'stable'
          cache: true

      - run: cp .env.example .env
      - run: flutter pub get

      - name: Retrieve subtracks.keystore
        env:
          SUBTRACKS_KEYSTORE_BASE64: ${{ secrets.SUBTRACKS_KEYSTORE_BASE64 }}
        run: |
          echo "$SUBTRACKS_KEYSTORE_BASE64" | base64 --decode > android/subtracks.keystore
      - name: Retrieve key.properties
        env:
          SUBTRACKS_KEYPROPERTIES_BASE64: ${{ secrets.SUBTRACKS_KEYPROPERTIES_BASE64 }}
        run: |
          echo "$SUBTRACKS_KEYPROPERTIES_BASE64" | base64 --decode > android/key.properties
      
      - run: flutter build apk -PsignRelease

      - run: mv build/app/outputs/flutter-apk/app-release.apk subtracks-${SUBTRACKS_VERSION}.apk
      - uses: actions/upload-artifact@v3
        with:
          name: subtracks-release-apk
          path: subtracks-*.apk

  build-aab:
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v3

      - name: Get subtracks version
        run: echo "SUBTRACKS_VERSION=$(yq '.version' pubspec.yaml)" >> $GITHUB_ENV

      - uses: subosito/flutter-action@v2
        with:
          flutter-version: '3.7.11'
          channel: 'stable'
          cache: true

      - run: cp .env.example .env
      - run: flutter pub get

      - name: Retrieve subtracks.keystore
        env:
          SUBTRACKS_KEYSTORE_BASE64: ${{ secrets.SUBTRACKS_KEYSTORE_BASE64 }}
        run: |
          echo "$SUBTRACKS_KEYSTORE_BASE64" | base64 --decode > android/subtracks.keystore
      - name: Retrieve key.properties
        env:
          SUBTRACKS_KEYPROPERTIES_BASE64: ${{ secrets.SUBTRACKS_KEYPROPERTIES_BASE64 }}
        run: |
          echo "$SUBTRACKS_KEYPROPERTIES_BASE64" | base64 --decode > android/key.properties

      - run: flutter build appbundle -PsignRelease

      - run: mv build/app/outputs/bundle/release/app-release.aab subtracks-${SUBTRACKS_VERSION}.aab
      - uses: actions/upload-artifact@v3
        with:
          name: subtracks-release-aab
          path: subtracks-*.aab
