default_platform(:ios)
build_number = 1000000000 + number_of_commits()

platform :ios do
  desc "Setup the LunaSea Keychain"
  lane :prepare_keychain do
    create_keychain(
      name: ENV["MATCH_KEYCHAIN_NAME"],
      password: ENV["MATCH_KEYCHAIN_PASSWORD"],
      default_keychain: is_ci,
      unlock: true,
      timeout: 3600,
      lock_when_sleeps: false
    )

    # Development
    match(
      type: "development",
      readonly: is_ci,
      keychain_name: ENV['MATCH_KEYCHAIN_NAME'],
      keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"],
    )
    
    # App Store Connect
    match(
      type: "appstore",
      readonly: is_ci,
      keychain_name: ENV['MATCH_KEYCHAIN_NAME'],
      keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"],
    )
  end

  desc "Destroy the LunaSea Keychain"
  lane :destroy_keychain do
    delete_keychain(name: ENV["MATCH_KEYCHAIN_NAME"])
  end

  desc "Build App Package"
  lane :build do
    prepare_keychain

    sh(
      "flutter", "build", "ios",
      "--release",
      "--bundle-sksl-path=shaders/ios_sksl.json",
      "--no-codesign",
      "--build-number=#{build_number}",
    )
    build_ios_app(
      scheme: "Runner",
      workspace: "Runner.xcworkspace",
      export_method: "app-store",
      export_options: {
        "app.lunasea.lunasea" => "Provisioning Profile Name",
        "app.lunasea.lunasea.ImageNotification" => "Provisioning Profile Name 2"
      },
    )

    destroy_keychain
  end

  desc "Deploy to App Store Connect"
  lane :deploy do |options|
    api_key = app_store_connect_api_key(
      key_id: ENV["APPLE_STORE_CONNECT_KEY_ID"],
      issuer_id: ENV["APPLE_STORE_CONNECT_ISSUER_ID"],
      key_filepath: ENV["APPLE_STORE_CONNECT_KEY_FILEPATH"],
    )

    upload_to_testflight(
      changelog: "Thank you for testing pre-release builds of LunaSea! Please consider joining the Discord to give feedback to the developer.\n\nChanges can be found on GitHub or by going to settings/system and tapping on the version tile!",
      distribute_external: true,
      groups: options[:groups] || "internal",
      ipa: options[:ipa] || "../ios/Runner.ipa",
      notify_external_testers: true,
    )
  end
end
