# Customise this file, documentation can be found here:
# https://github.com/fastlane/fastlane/tree/master/fastlane/docs
# All available actions: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Actions.md
# can also be listed using the `fastlane actions` command

# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`

# If you want to automatically update fastlane if a new version is available:
# update_fastlane

# This is the minimum version number required.
# Update this, if you use features of a newer version
fastlane_version "2.144.0"

default_platform :android

platform :android do

  # Extract Application Id from gradle file
  def get_application_id(flavor = nil, path = '../app/build.gradle', constant_name = 'applicationId')
    application_id = nil
    application_id_suffix = nil
    toggle_flavors = false
    current_flavor = nil
    unless File.file?(path)
      UI.message(" -> No file exists at path: (#{path})!")
      return application_id
    end
    begin
      file = File.new(path, 'r')
      while (line = file.gets)
        next unless line.include? constant_name
        components = line.strip.split(' ')
        application_id = components[components.length - 1].tr("\"", '')
        UI.message("#{constant_name} = #{application_id}")
        break
      end
      if flavor
        file.each do |line|
          if line[/^(#.*)?$/]
            next
          end
        	#UI.message("Line = #{line.tr("\n",'')}")
          if toggle_flavors
            current_flavor = line[/(?=\s*)\w+(?=\s+\{)/]
            if ! current_flavor
              break
            end 
            #UI.message("Flavor = #{current_flavor}")
            toggle_flavors = false
            next
          end
          if current_flavor == flavor and line.include? "#{constant_name}Suffix"
            components = line.strip.split(' ')
            application_id_suffix = components[components.length - 1].tr("\"", '')
            UI.message("#{constant_name}Suffix = #{application_id_suffix}")
            next
          end
          if line[/\s*}/]
          	if current_flavor
          	  current_flavor = nil
          	  toggle_flavors = true
          	  next
          	end
            if toggle_flavors
              break
            end
            next
          end
          if line[/(?=\s*)productFlavors(?=\s+\{)/]
            toggle_flavors = true
            next
          end
        end
      end
      file.close
    rescue => err
      UI.error("An exception occurred while reading the gradle file: #{err}")
      err
    end
    return "#{application_id}#{application_id_suffix}"
  end

  # Define flavor name for deploy branch
  def getFlavorName(options)
    flavor = nil
    if options and options[:fl_branch] and ! options[:fl_branch][/.*_.*/]
      # Use option if provided
      flavor = options[:fl_branch]
    else
      # Fallback on environment variable if any
      if ENV['BRANCH_NAME'] and ! ENV['BRANCH_NAME'][/.*_.*/]
        flavor = ENV['BRANCH_NAME']
      end
    end
    if flavor == 'master'
      flavor = 'production'
    end
    if flavor == nil or flavor == ''  
      # Choose default flavor
      flavor = 'dev2'
    end
    return flavor
  end

  # Define package name for a branch
  def getPackageName(options = nil)
    return get_application_id(getFlavorName(options))
  end

  # Extract version_name from environment var named VERSION
  def getVersionName(options = nil)
    version_name = ENV['VERSION'] ? ENV['VERSION'].split('-')[0] : nil
    return version_name
  end

  # Extract version_code from environment var named VERSION
  def getVersionCode(options = nil)
    version_code = ENV['VERSION'] ? ENV['VERSION'].split('-')[1] : nil
    return version_code
  end

  before_all do |lane, options|
    # ENV["SLACK_URL"] = "https://hooks.slack.com/services/..."
  end

  desc "Display infos about the app"
  lane :info do |options|
  	UI.message("App version name = #{getVersionName()}")
  	UI.message("App version number = #{getVersionCode()}")
    UI.message("App Flavor = #{getFlavorName(options)}")
  	UI.message("App ID = #{getPackageName(options)}")
  end

  desc "Run all the tests"
  lane :test do |options|
    gradle(
      task: "test",
      build_type: 'Release',
      flavor: "production",
    )
    gradle(
      task: "test",
      build_type: 'Release',
      flavor: "acceptance",
    )
  end

  desc "Build the apk"
  lane :build do |options|
    gradle(
      task: "clean assemble",
      build_type: 'Release',
      flavor: "#{getFlavorName(options)}",
    )
  end

  desc "Bump version code/build number"
  private_lane :bump do |options|
    increment_version_code(
      var_name: "versionCode|versionBuild",
      verbose: true,
    )
  end

  desc "Tag as a new version"
  private_lane :tag do |options|
    git_commit(
      path: "app/build.gradle",
      message: "Increment version code to #{lane_context[SharedValues::VERSION_CODE]} for next release",
    )
    add_git_tag(
      tag: "#{ENV['VERSION']}-#{lane_context[SharedValues::VERSION_CODE]}",
      message: "Create new tag for version #{ENV['VERSION']}-#{lane_context[SharedValues::VERSION_CODE]}",
    )
    push_to_git_remote(
      local_branch: "HEAD",
      remote_branch: "master",
    )
  end

  desc "Build and deploy the apk for Alpha testing in Google Play store"
  lane :deploy_alpha do |options|
    bump
    gradle(
      task: "clean assemble",
      build_type: 'Release',
    )
    sh("cp -vf metadata/android/en-US/changelogs/latest.txt metadata/android/en-US/changelogs/#{lane_context[SharedValues::VERSION_CODE]}.txt")
    sh("git add metadata/android/en-US/changelogs/#{lane_context[SharedValues::VERSION_CODE]}.txt")
    sh("git add metadata/android/en-US/changelogs/latest.txt")
    sh("cp -vf metadata/android/nl-NL/changelogs/latest.txt metadata/android/nl-NL/changelogs/#{lane_context[SharedValues::VERSION_CODE]}.txt")
    sh("git add metadata/android/nl-NL/changelogs/#{lane_context[SharedValues::VERSION_CODE]}.txt")
    sh("git add metadata/android/nl-NL/changelogs/latest.txt")
    git_commit(
      path: [
        "fastlane/metadata/android/en-US/changelogs/latest.txt",
        "fastlane/metadata/android/en-US/changelogs/#{lane_context[SharedValues::VERSION_CODE]}.txt",
        "fastlane/metadata/android/nl-NL/changelogs/latest.txt",
        "fastlane/metadata/android/nl-NL/changelogs/#{lane_context[SharedValues::VERSION_CODE]}.txt",
      ],
      message: "Provide changelogs for this version",
    )
    supply(
      apk: "app/build/outputs/apk/#{getFlavorName(options)}/release/app-#{getFlavorName(options)}-release.apk",
      mapping: "app/build/outputs/apk/#{getFlavorName(options)}/release/mapping.txt",
      track: 'alpha',
      skip_upload_apk: false,
      skip_upload_metadata: false,
      skip_upload_images: true,
      skip_upload_screenshots: true,
    )
    tag
  end

  desc "Update metadata only, including images and screenshots"
  lane :deploy_metadata do |options|
    supply(
      skip_upload_apk: true,
      skip_upload_metadata: false,
      skip_upload_images: false,
      skip_upload_screenshots: false,
    )
  end

  desc "Submit a new build to Crashlytics Beta"
  lane :beta_crash do |options|
    gradle(task: "assembleRelease")
    crashlytics(
      api_token: "b439e4099424e0f33cdab4e7b689b60c4bc3a5d2",
      build_secret: "ecffdd52c995054f79161c3570ed769f2bacf2dd3082e2aba7489b147c29ce7d"
    )
  end
  

  desc "Submit a new build to Firebase App Distribution"
  lane :beta_firebase do |options|
    gradle(task: "assembleRelease")
    firebase_app_distribution(
      app: "1:79978046456:android:ec6742f538f9269b",
      apk_path: "app/build/outputs/apk/#{getFlavorName(options)}/release/app-#{getFlavorName(options)}-release.apk",
    )
  end

  desc "Deploy a new version to the Google Play"
  lane :alpha do |options|
    supply(
      apk: "app/build/outputs/apk/#{getFlavorName(options)}/release/app-#{getFlavorName(options)}-release.apk",
      mapping: "app/build/outputs/apk/#{getFlavorName(options)}/release/mapping.txt",
      track: 'alpha',
      skip_upload_apk: false,
      skip_upload_metadata: false,
      skip_upload_images: false,
      skip_upload_screenshots: false,
      package_name: "#{getPackageName(options)}",
    )
  end

  desc "Deploy a new version to the Google Play"
  lane :beta do |options|
    supply(
      track: 'alpha',
      track_promote_to: 'beta',
      skip_upload_apk: true,
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
      package_name: "#{getPackageName(options)}",
      version_code: getVersionCode(),
    )
  end

  desc "Deploy a new version to the Google Play"
  lane :production do |options|
    supply(
      track: 'beta',
      track_promote_to: 'production',
      skip_upload_apk: true,
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true,
      package_name: "#{getPackageName(options)}",
      version_code: getVersionCode(),
    )
  end

  # You can define as many lanes as you want

  after_all do |lane, options|
    # This block is called, only if the executed lane was successful

    # slack(
    #   message: "Successfully deployed new App Update."
    # )
  end

  error do |lane, exception|
    # slack(
    #   message: exception.message,
    #   success: false
    # )
  end
end


# More information about multiple platforms in fastlane: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Platforms.md
# All available actions: https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Actions.md

# fastlane reports which actions are used
# No personal data is sent or shared. Learn more at https://github.com/fastlane/enhancer
