default_platform(:ios)

platform :ios do
  desc "Create the LunaSea Keychain"
  lane :keychain_create 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
    )
  end

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

  desc "Setup the Keychain"
  lane :keychain_setup do
    # Development
    match(
      type: "development",
      readonly: is_ci,
      keychain_name: ENV['MATCH_KEYCHAIN_NAME'],
      keychain_password: ENV["MATCH_KEYCHAIN_PASSWORD"],
    )

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

  desc "Connect to App Store Connect"
  lane :connect_appstore_connect do
    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"],
    )
  end

  desc "Build App Package for App Store"
  lane :build_appstore do |options|
    keychain_create
    keychain_setup

    sh(
      "flutter", "build", "ios",
      "--release",
      "--no-codesign",
      "--build-number=#{options[:build_number]}",
    )
    build_ios_app(
      scheme: "Runner",
      workspace: "Runner.xcworkspace",
      export_method: "app-store",
      codesigning_identity: ENV["IOS_CODESIGNING_IDENTITY"],
      export_options: {
        provisioningProfiles: {
          "app.lunasea.lunasea" => "match AppStore app.lunasea.lunasea"
        }
      }
    )
    sh("mkdir", "-p", "../../output")
    sh("mv", "../../ios/Runner.ipa", "../../output/lunasea-ios.ipa")

    keychain_delete
  end

  desc "Deploy to App Store Connect"
  lane :deploy_appstore do |options|
    connect_appstore_connect

    upload_to_testflight(
      changelog: File.read("./changelog.txt"),
      distribute_external: true,
      groups: options[:groups],
      ipa: options[:ipa],
      notify_external_testers: true,
    )
  end
end
