# 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)

ROLLOUT = "0.05"
WEAR_TRACK = "wear:internal" # don't need to hold up reviews

def version_code
  Integer(File.read("../version.properties")[/^\s*VERSION_CODE\s*=\s*(\d+)/, 1])
end

def wear_version_code
  version_code + 1
end

def highest(track)
  google_play_track_version_codes(track: track).max
end

def upload(track:, aab:, mapping:, version_code:, rollout: nil)
  current = highest(track)
  if current && current >= version_code
    UI.message("#{track} already has #{current}, skipping #{version_code}")
    return
  end
  upload_to_play_store(
    aab: aab,
    mapping: mapping,
    track: track,
    rollout: rollout,
    skip_upload_apk: true,
    skip_upload_metadata: true,
    skip_upload_images: true,
    skip_upload_screenshots: true,
  )
end

platform :android do
  desc "Upload to a track, production rolls out to 5%"
  lane :deploy do |options|
      track = options.fetch(:track)
      upload(
        track: track,
        aab: "app/build/outputs/bundle/googleplayRelease/app-googleplay-release.aab",
        mapping: "app/build/outputs/mapping/googleplayRelease/mapping.txt",
        version_code: version_code,
        rollout: track == "production" ? ROLLOUT : nil,
      )
      upload(
        track: WEAR_TRACK,
        aab: "wear/build/outputs/bundle/release/wear-release.aab",
        mapping: "wear/build/outputs/mapping/release/mapping.txt",
        version_code: wear_version_code,
      )
  end

  desc "Fail if VERSION_CODE is not bumped"
  lane :check_version_code do |options|
    tracks = options.fetch(:track) == "beta" ? ["production", "beta"] : ["production"]
    tracks.each do |track|
      current = highest(track)
      if current && current >= version_code
        UI.user_error!("#{track} already has #{current}, bump VERSION_CODE past it")
      end
    end
    taken = ["production", "beta", WEAR_TRACK].flat_map { |track| google_play_track_version_codes(track: track) }
    clash = [version_code, wear_version_code] & taken
    UI.user_error!("#{clash.join(", ")} already on Play, bump VERSION_CODE") unless clash.empty?
  end

  desc "Download Play-signed universal APK"
  lane :download_signed_apk do
    download_universal_apk_from_google_play(
      package_name: "org.tasks",
      version_code: version_code,
      json_key: "./fastlane.json",
      destination: "tasks-googleplay-release.apk",
    )
  end

  desc "Lint"
  lane :lint do
    gradle(task: ":app:lintGoogleplayRelease :app:lintGenericRelease --no-configuration-cache")
  end

  desc "Bundle"
  lane :bundle do
        gradle(
            task: "app:bundleGoogleplayRelease wear:bundleRelease",
            properties: {
                "tasksKeyAlias": ENV["KEY_ALIAS"],
                "tasksStoreFile": ENV["KEY_PATH"],
                "tasksStorePassword": ENV["KEY_STORE_PASSWORD"],
                "tasksKeyPassword": ENV["KEY_PASSWORD"],
                "tasks_mapbox_key": ENV["MAPBOX_KEY"],
                "tasks_google_key": ENV["GOOGLE_KEY"],
                "tasks_posthog_key": ENV["POSTHOG_KEY"]
            }
        )
        generate_apks
  end

  desc "Generate universal APKs from AABs using bundletool"
  private_lane :generate_apks do
    bundletool_version = "1.17.2"
    bundletool = "bundletool.jar"
    unless File.exist?("../#{bundletool}")
      sh("curl -sSLf --retry 5 --retry-all-errors https://github.com/google/bundletool/releases/download/#{bundletool_version}/bundletool-all-#{bundletool_version}.jar -o ../#{bundletool}")
    end

    bundles = [
      "app/build/outputs/bundle/googleplayRelease/app-googleplay-release",
      "wear/build/outputs/bundle/release/wear-release",
    ]

    bundles.each do |base|
      aab = "../#{base}.aab"
      apk = "../#{base}.apk"
      apks = "../#{base}.apks"
      sh(
        "java", "-jar", "../#{bundletool}",
        "build-apks",
        "--bundle=#{aab}",
        "--output=#{apks}",
        "--mode=universal",
        "--ks=#{ENV['KEY_PATH']}",
        "--ks-key-alias=#{ENV['KEY_ALIAS']}",
        "--ks-pass=pass:#{ENV['KEY_STORE_PASSWORD']}",
        "--key-pass=pass:#{ENV['KEY_PASSWORD']}",
        "--overwrite",
      )
      sh("unzip", "-o", apks, "universal.apk", "-d", File.dirname(apk))
      File.rename(File.join(File.dirname(apk), "universal.apk"), apk)
      File.delete(apks)
    end
  end
end
