default_platform(:ios)

platform :ios do
  desc "Build a release tag and upload it to TestFlight"
  lane :beta do
    setup_ci

    match(type: "appstore")

    tag = ENV.fetch("GITHUB_REF_NAME")
    version = tag[%r{\Arelease/v(\d+\.\d+\.\d+)\z}, 1]
    UI.user_error!("Expected a tag in the form release/vX.X.X; got #{tag.inspect}") unless version

    build_number = ENV.fetch("GITHUB_RUN_NUMBER")
    UI.user_error!("GITHUB_RUN_NUMBER must be a positive integer") unless build_number.match?(/\A[1-9]\d*\z/)

    update_info_plist(
      plist_path: "XIONControlPanel/SupportingFiles/Info.plist",
      block: proc do |plist|
        plist["CFBundleShortVersionString"] = version
        plist["CFBundleVersion"] = build_number
      end
    )

    api_key = app_store_connect_api_key(
      key_id: ENV.fetch("APP_STORE_CONNECT_API_KEY_ID"),
      issuer_id: ENV.fetch("APP_STORE_CONNECT_API_ISSUER_ID"),
      key_content: ENV.fetch("APP_STORE_CONNECT_API_KEY"),
      is_key_content_base64: true
    )

    build_app(scheme: "XIONControlPanel")

    upload_to_testflight(
      api_key: api_key,
      skip_waiting_for_build_processing: true,
      uses_non_exempt_encryption: false
    )
  end
end
