# 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
  lane :internal do
#     Dir.chdir("..") do
#       sh("flutter build appbundle --flavor play")
#     end

    upload_to_play_store(
      track: 'internal',
      aab: './build/app/outputs/bundle/playRelease/app-play-release.aab',
      skip_upload_apk: 'true',
      skip_upload_metadata: 'true',
      skip_upload_images: 'true',
      skip_upload_screenshots: 'true',
    )
  end

  lane :alpha do
    upload_to_play_store(
      track: 'internal', 
      track_promote_to: 'alpha', 
      version_code: get_code(),
      skip_upload_aab: 'true', 
      skip_upload_apk: 'true',
      skip_upload_metadata: 'true',
      skip_upload_images: 'true',
      skip_upload_screenshots: 'true',
    )
  end

  lane :beta do
    upload_to_play_store(
      track: 'alpha', 
      track_promote_to: 'beta', 
      version_code: get_code(),
      skip_upload_aab: 'true', 
      skip_upload_apk: 'true',
      skip_upload_metadata: 'true',
      skip_upload_images: 'true',
      skip_upload_screenshots: 'true',
    )
  end

  lane :meta do
    upload_to_play_store(
      track: 'beta', 
      version_code: get_code(),
      skip_upload_aab: 'true', 
      skip_upload_apk: 'true',
    )
  end

  lane :github do 
#     Dir.chdir("..") do
#       sh("flutter build apk --flavor play")
#     end

    version = get_version()
    code = get_code()

    set_github_release(
      repository_name: "vauvenal5/yaga",
#       api_token: ENV["GITHUB_TOKEN"], # for local use
      api_bearer: ENV["GITHUB_TOKEN"], # for Github actions
      name: version,
      tag_name: version,
      description: (File.read("metadata/android/en-US/changelogs/"+code.to_s+".txt") rescue "No changelog provided."),
      commitish: "master",
      upload_assets: ["./build/app/outputs/flutter-apk/app-play-release.apk"]
    )
  end

  def get_version_or_code(capture)
    pubspec = File.read('../pubspec.yaml')
    regex = /version:\s(\d+\.\d+\.\d+)\+(\d+)/
    return pubspec[regex, capture]
  end

  def get_version()
    return "v"+get_version_or_code(1)
  end

  def get_code()
    return get_version_or_code(2).to_i
  end
end
