# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

default_platform(:android)

platform :android do
  desc "Fetch latest production version code from Google Play"
  lane :get_latest_production_version do
    # Fetch latest codes
    track_version_codes = google_play_track_version_codes(track: "production")
    # Return the maximum
    track_version_codes.max
  end

  desc "Bumps version code in gradle file"
  lane :bump_version_code do
    path = '../app/build.gradle'
    re = /versionCode\s+(\d+)/

    last_version_code = get_latest_production_version

    s = File.read(path)
    s[re, 1] = (last_version_code + 1).to_s

    f = File.new(path, 'w')
    f.write(s)
    f.close
  end

  desc "Build release bundle"
  lane :build_release_bundle do
    gradle(task: "clean app:bundleRelease")
  end

  desc "Deploy a new version to the Google Play"
  lane :deploy do
    bump_version_code
    build_release_bundle
    upload_to_play_store(
      mapping: "app/build/outputs/mapping/release/mapping.txt"
    )
  end
end
