default_platform(:ios)

platform :ios do
  desc "Upload the signed IPA to TestFlight without EAS Submit"
  lane :beta do
    ipa = ENV.fetch("IPA_PATH")
    UI.user_error!("IPA_PATH must point to an existing .ipa file") unless File.file?(ipa) && File.extname(ipa) == ".ipa"

    api_key = app_store_connect_api_key(
      key_id: ENV.fetch("ASC_KEY_ID"),
      issuer_id: ENV.fetch("ASC_ISSUER_ID"),
      key_content: ENV.fetch("ASC_PRIVATE_KEY"),
      in_house: false
    )

    upload_to_testflight(
      api_key: api_key,
      ipa: ipa,
      app_identifier: "run.openbot.mobile",
      skip_waiting_for_build_processing: true,
      distribute_external: false
    )
  end
end

platform :android do
  desc "Upload the signed AAB to a Google Play testing track without EAS Submit"
  lane :play do
    aab = ENV.fetch("AAB_PATH")
    UI.user_error!("AAB_PATH must point to an existing .aab file") unless File.file?(aab) && File.extname(aab) == ".aab"
    track = ENV.fetch("PLAY_TRACK")
    UI.user_error!("PLAY_TRACK must be internal or alpha") unless %w[internal alpha].include?(track)
    release_status = ENV.fetch("PLAY_RELEASE_STATUS")
    UI.user_error!("PLAY_RELEASE_STATUS must be completed or draft") unless %w[completed draft].include?(release_status)

    upload_to_play_store(
      package_name: "run.openbot.mobile",
      aab: aab,
      json_key_data: ENV.fetch("GOOGLE_PLAY_SERVICE_ACCOUNT_KEY"),
      track: track,
      release_status: release_status,
      skip_upload_apk: true,
      skip_upload_metadata: true,
      skip_upload_changelogs: true,
      skip_upload_images: true,
      skip_upload_screenshots: true
    )
  end

  desc "Download the universal APK that Google Play makes from an uploaded bundle"
  lane :apk do
    version_code = ENV.fetch("VERSION_CODE")
    UI.user_error!("VERSION_CODE must be the build number of a bundle on Google Play") unless version_code.match?(/\A\d+\z/)

    # Google Play signs this APK with the app signing key, so it has the signature of the store app.
    download_universal_apk_from_google_play(
      package_name: "run.openbot.mobile",
      version_code: version_code,
      json_key_data: ENV.fetch("GOOGLE_PLAY_SERVICE_ACCOUNT_KEY"),
      destination: ENV.fetch("APK_PATH")
    )
  end
end
