# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.


# This workflow uses perl regex. For better syntaxis understading see these docs:
# https://perldoc.perl.org/perlrequick#Search-and-replace
# https://perldoc.perl.org/perlre#Other-Modifiers

name: Create new release

run-name: Release v${{ inputs.version }}

on:
  workflow_dispatch:
    inputs:
      version:
        description: "Version"
        required: true
        type: string
      release-notes:
        description: "Release notes"
        required: true
        type: string
      github-release:
        type: boolean
        description: Create Github release
        default: true
      google-play-release:
        type: boolean
        description: Create Google Play release
        default: true
      include-iap:
        type: boolean
        description: Include IAP package
        default: true

env:
  BUILD_ARGS: --release --flavor prod --dart-define cameraPreviewAspectRatio=240/320 -t lib/main_prod.dart

jobs:
  build:
    name: Build .apk & .aab
    if: ${{ inputs.github-release || inputs.google-play-release }}
    runs-on: macos-11
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Connect private iap package
        uses: webfactory/ssh-agent@v0.8.0
        if: ${{ inputs.include-iap }}
        with:
          ssh-private-key: ${{ secrets.M3_LIGHTMETER_IAP_KEY }}

      - name: Override iap package with stub
        if: ${{ !inputs.include-iap }}
        run: | 
          echo "\ndependency_overrides:\n  m3_lightmeter_iap:\n    path: iap" >> pubspec.yaml

      - uses: actions/setup-java@v3
        with:
          distribution: "zulu"
          java-version: "11"

      - name: Restore Android keystore .jsk and .properties files
        env:
          KEYSTORE: ${{ secrets.KEYSTORE }}
          KEYSTORE_PROPERTIES: ${{ secrets.KEYSTORE_PROPERTIES }}
        run: |
          KEYSTORE_PATH=$RUNNER_TEMP/keystore.jks
          echo -n "$KEYSTORE" | base64 --decode --output $KEYSTORE_PATH
          cp $KEYSTORE_PATH ./android/app
          KEYSTORE_PROPERTIES_PATH=$RUNNER_TEMP/key.properties
          echo -n "$KEYSTORE_PROPERTIES" | base64 --decode --output $KEYSTORE_PROPERTIES_PATH
          cp $KEYSTORE_PROPERTIES_PATH ./android

      - name: Restore android/app/google-services.json
        env:
          GOOGLE_SERVICES_JSON_ANDROID: ${{ secrets.GOOGLE_SERVICES_JSON_ANDROID }}
        run: |
          GOOGLE_SERVICES_JSON_ANDROID_PATH=$RUNNER_TEMP/google-services.json
          echo -n "$GOOGLE_SERVICES_JSON_ANDROID" | base64 --decode --output $GOOGLE_SERVICES_JSON_ANDROID_PATH
          cp $GOOGLE_SERVICES_JSON_ANDROID_PATH ./android/app

      - name: Restore firebase_options.dart
        env:
          FIREBASE_OPTIONS: ${{ secrets.FIREBASE_OPTIONS }}
        run: |
          FIREBASE_OPTIONS_PATH=$RUNNER_TEMP/firebase_options.dart
          echo -n "$FIREBASE_OPTIONS" | base64 --decode --output $FIREBASE_OPTIONS_PATH
          cp $FIREBASE_OPTIONS_PATH ./lib

      # This step makes sense when Github release is enabled because this release increments the build number.
      # Therefore here we have to increment it as well to build an apk with the same build number.
      - name: Increment build number & replace version number
        if: ${{ inputs.github-release }}
        run: perl -i -pe 's/^(version:\s+)(\d+\.\d+\.\d+)(\+)(\d+)$/$1."${{ github.event.inputs.version }}".$3.($4+1)/e' pubspec.yaml

      - name: Install Flutter
        uses: subosito/flutter-action@v2
        with:
          channel: "stable"
          flutter-version: '3.10.0'

      - name: Prepare flutter project
        run: |
          flutter --version
          flutter pub get
          flutter pub run intl_utils:generate

      - name: Build apk
        if: ${{ inputs.github-release }}
        run: flutter build apk $BUILD_ARGS

      - name: Upload apk to artifacts
        if: ${{ inputs.github-release }}
        uses: actions/upload-artifact@v3
        with:
          name: m3_lightmeter_apk
          path: build/app/outputs/flutter-apk/app-prod-release.apk

      - name: Build appbundle
        if: ${{ inputs.google-play-release }}
        run: flutter build appbundle $BUILD_ARGS

      - name: Upload app bundle to artifacts
        if: ${{ inputs.google-play-release }}
        uses: actions/upload-artifact@v3
        with:
          name: m3_lightmeter_bundle
          path: build/app/outputs/bundle/prodRelease/app-prod-release.aab

  generate-release-notes:
    name: Generate release notes
    runs-on: ubuntu-latest
    steps:
      - name: Generate release notes
        run: |
          echo ${{ inputs.release-notes }} > whatsnew-en-US.md
          perl -i -pe 's/\s{1}(-{1})/\n$1/g' whatsnew-en-US.md

      - name: Upload merged_native_libs.zip to artifacts
        uses: actions/upload-artifact@v3
        with:
          name: whatsnew-en-US
          path: whatsnew-en-US.md

  update-version-in-repo:
    name: Update repo version
    if: ${{ inputs.github-release }}
    needs: [build]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Increment build number & replace version number
        run: perl -i -pe 's/^(version:\s+)(\d+\.\d+\.\d+)(\+)(\d+)$/$1."${{ github.event.inputs.version }}".$3.($4+1)/e' pubspec.yaml

      - name: Commit changes
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git add -A
          git commit -m "Version bump"

      - name: Push to main
        uses: CasperWA/push-protected@v2
        with:
          token: ${{ secrets.PUSH_TO_MAIN_TOKEN }}
          branch: ${{ github.ref_name }}
          unprotect_reviews: true

  create-github-release:
    name: Create Github release
    if: ${{ inputs.github-release }}
    needs: [build, generate-release-notes, update-version-in-repo]
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Download apk
        uses: actions/download-artifact@v3
        with:
          name: m3_lightmeter_apk

      - name: Rename apk
        run: mv app-prod-release.apk m3_lightmeter.apk

      - name: Download release notes
        uses: actions/download-artifact@v3
        with:
          name: whatsnew-en-US

      - uses: ncipollo/release-action@v1.12.0
        with:
          artifacts: "m3_lightmeter.apk"
          skipIfReleaseExists: true
          tag: "v${{ github.event.inputs.version }}"
          bodyFile: "whatsnew-en-US.md"

      - name: Delete apk artifact
        uses: geekyeggo/delete-artifact@v2
        with:
          name: m3_lightmeter_apk

  create-google-play-release:
    name: Create Google Play release
    if: ${{ inputs.google-play-release }}
    needs: [build, generate-release-notes]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          submodules: recursive

      - name: Download app bundle
        uses: actions/download-artifact@v3
        with:
          name: m3_lightmeter_bundle

      - name: Extract & zip merged_native_libs
        run: |
          unzip app-prod-release.aab
          (cd base/lib && zip -r "$OLDPWD/merged_native_libs.zip" .)

      - name: Download release notes
        uses: actions/download-artifact@v3
        with:
          name: whatsnew-en-US

      - name: Move release notes to a folder
        run: |
          mv whatsnew-en-US.md whatsnew-en-US
          mkdir whatsnew
          mv whatsnew-en-US whatsnew

      # https://unix.stackexchange.com/questions/13466/can-grep-output-only-specified-groupings-that-match'
      # https://stackoverflow.com/questions/74353311/github-workflow-unable-to-process-file-command-env-successfully
      - name: Create Google Play release name
        id: release-name
        run: |
          RELEASE_NAME=$(echo "$(cat pubspec.yaml)" | sed -n -r "s/^version:\s{1}(.*)[+](.*)$/700\2 (\1)/p")
          echo "release_name=$RELEASE_NAME" >> $GITHUB_ENV

      - name: Create Google Play release
        id: create-google-play-release-step
        uses: r0adkll/upload-google-play@v1.1.1
        with:
          serviceAccountJsonPlainText: ${{ secrets.GH_ACTIONS_SERVICE_ACCOUNT_JSON }}
          packageName: com.vodemn.lightmeter
          releaseFiles: app-prod-release.aab
          releaseName: ${{ env.release_name }}
          track: production
          status: completed
          debugSymbols: merged_native_libs.zip
          whatsNewDirectory: whatsnew

      # https://docs.github.com/en/actions/learn-github-actions/expressions#failure-with-conditions
      - name: Zip app bundle and merged_native_libs
        if: ${{ failure() && steps.create-google-play-release-step.conclusion == 'failure' }}
        run: zip m3_lightmeter_release.zip app-prod-release.aab merged_native_libs.zip

      - name: Upload release zip to artifacts
        if: ${{ failure() && steps.create-google-play-release-step.conclusion == 'failure' }}
        uses: actions/upload-artifact@v3
        with:
          name: m3_lightmeter_release
          path: m3_lightmeter_release.zip
          
      - name: Delete app bundle & merged native libs artifacts
        if: ${{ always() }}
        uses: geekyeggo/delete-artifact@v2
        with:
          name: m3_lightmeter_bundle

  cleanup:
    name: Cleanup
    if: ${{ always() }}
    needs: [create-github-release, create-google-play-release]
    runs-on: ubuntu-latest
    steps:
      - name: Delete release notes artifact
        uses: geekyeggo/delete-artifact@v2
        with:
          name: whatsnew-en-US