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

fastlane_require "spaceship"

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

ENV["PROJ_PATH"] = "Code/Imgur.xcodeproj"


before_all do
  # cocoapods
end


platform :ios do
    desc "Delivery Daily Build using Firebase"
    lane :distribute do |options|

        release = firebase_app_distribution(
            app: "1:972715825012:ios:56c5f3dd09699b506afe21",
            service_credentials_file: options[:plist],
            ipa_path: options[:ipa],
            testers: "lucas@imgur.com",
	          groups:  "qa-team",
            release_notes: "Lots of amazing new features to test out!",
	          debug: true
        )

    end
end


desc "Set a new version. Options:"
desc "version:<version>\te.g. version:2.1.5"
lane :setversion do |options|
  raise 'No version provided, use version:<version> as argument' unless options[:version]
  increment_version_number(
    xcodeproj: ENV["PROJ_PATH"],
    version_number: options[:version]
  )
end

desc "Print the current version and build"
lane :whatversion do 
  puts "Current version: " + get_version_number(xcodeproj: ENV["PROJ_PATH"]) + " (" + get_build_number(xcodeproj: ENV["PROJ_PATH"]) + ")"
end

desc "Upload dSYMs for current app version"
lane :upload_dsyms do |options|
  username = options[:username]
  app_version = options[:version]

  raise 'Provide your Apple account ID to sign in' unless username

  download_dsyms(
    team_id: 2036292,
    username: username,
    version: app_version || get_version_number(xcodeproj: ENV["PROJ_PATH"], target: "Imgur")
  )
  upload_symbols_to_crashlytics(
    gsp_path: "Code/Imgur/Common/Global Helpers/Supporting Files/Firebase-Production.plist"
  )
  clean_build_artifacts
end

desc "Cull testers that haven't installed in a while"
desc "username:yours\tprovide an admin-level account to do the changes (iosci doesn't have permission)"
lane :cull_testers do |options|
  # 90 days ago
  minimum_install_time = (Date.today - 120).to_time
  minimum_install_seconds = minimum_install_time.to_i

  puts "Deleting testers without installs since " + minimum_install_time.strftime("%m/%d/%y %H:%M")

  puts "Logging in..."

  Spaceship::Tunes::login(options[:username])

  puts "Logged in, searching for testers..."

  ext_testers = Spaceship::TestFlight::Tester.all(app_id: "639881495").select { |tester|     
    if tester.email.include? "@imgur.com"
      puts "Skipping #{tester.email} because they are an Imgur email address."
      next(false)
    end

    if tester.latest_installed_date.nil?
      next(true)
    end

    # install date is in milliseconds but the docs say seconds.. ok..
    (tester.latest_installed_date / 1000) < minimum_install_seconds
  }

  if ext_testers.empty?
    raise "No testers to delete, bailing out"
  end

  empty_install_count = ext_testers.select { |tester| tester.latest_installed_date.nil? }.count
  latest_install_time = ext_testers.map { |tester| tester.latest_installed_date }.compact.max

  puts "Deleting #{ext_testers.count} testers: #{empty_install_count.to_s} for non-install, #{ext_testers.count - empty_install_count} for old installs"

  if latest_install_time.nil?
    puts "Sanity check: none of the people to delete have a latest install date"
  else
    puts "Sanity check: latest install date was #{Time.at(latest_install_time / 1000).strftime("%m/%d/%y %H:%M")}"
  end

  if UI.confirm("Are you sure you want to delete #{ext_testers.count} testers?")
    puts "Starting now, this may take a few minutes..."

    ext_testers.each { |tester| 
      tester.remove_from_app!(app_id: "639881495")
      puts "Deleted #{tester.email}"
    }

    puts "Deletions finished"
  else
    puts "Delete aborted"
  end
end

desc "Remove a specific tester or list of testers"
desc "users:comma,separated,list\tthe list of email addresses to remove"
desc "username:yours\tprovide an admin-level account to do the changes (iosci doesn't have permission)"
lane :remove_tester do |options|
  Spaceship::Tunes::login(options[:username])

  options[:users]
    .split(',')
    .map { |email| 
      Spaceship::Tunes::Tester::External.find(email)
    }
    .compact
    .each { |tester|
      tester.delete!
      puts "Removed tester #{tester.email}"
    }
end

desc "Apply formatting rules to Swift code"
lane :format do
  sh("swiftformat ../Code/")
end

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

error do |lane, exception|

end
