# Uncomment this line to define a global platform for your project
platform :ios, '13.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

require 'json'

# Firebase is Android-only: FCM is used solely by the `oneme` flavor, and on
# iOS there is a single `ru.komet.app` bundle that never initialises push.
# Keep the Firebase SDK out of the iOS build entirely so iOS is not forced up
# to the iOS 15 deployment target that firebase_core's podspec requires.
FIREBASE_IOS_PLUGINS = %w[firebase_core firebase_messaging].freeze

deps_file = File.expand_path('../.flutter-plugins-dependencies', __dir__)
if File.exist?(deps_file)
  deps = JSON.parse(File.read(deps_file))
  ios_plugins = deps.dig('plugins', 'ios')
  if ios_plugins
    ios_plugins.reject! { |p| FIREBASE_IOS_PLUGINS.include?(p['name']) }
    File.write(deps_file, JSON.generate(deps))
  end
end

registrant = File.expand_path('Runner/GeneratedPluginRegistrant.m', __dir__)
if File.exist?(registrant)
  src = File.read(registrant)
  FIREBASE_IOS_PLUGINS.each do |mod|
    cls = "FLT#{mod.split('_').map(&:capitalize).join}Plugin"
    m = Regexp.escape(mod)
    src = src.gsub(/#if __has_include\(<#{m}\/[^>]+>\).*?#endif\n/m, '')
    src = src.gsub(/^\s*#import <#{m}\/[^>]+>\n/, '')
    src = src.gsub(/^\s*@import #{m};\n/, '')
    src = src.gsub(/^\s*\[#{cls} registerWithRegistrar:.*\n/, '')
  end
  File.write(registrant, src)
end

project 'Runner', {
  'Debug' => :debug,
  'Profile' => :release,
  'Release' => :release,
}

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
  unless File.exist?(generated_xcode_build_settings_path)
    raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
  end

  File.foreach(generated_xcode_build_settings_path) do |line|
    matches = line.match(/FLUTTER_ROOT\=(.*)/)
    return matches[1].strip if matches
  end
  raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
  use_frameworks!

  pod 'rlottie', :path => '../third_party'
  flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
  target 'RunnerTests' do
    inherit! :search_paths
  end
end

# libopus ships with ogg_opus_player as a static xcframework. Nothing in the app
# references its encoder entry points, so the linker would drop them and
# `DynamicLibrary.process()` (OpusOggEncoder) would find nothing. Force-loading
# the slice keeps the whole library, which is what voice-message encoding needs.
#
# The slice is referenced in the plugin source tree rather than through
# `PODS_XCFRAMEWORKS_BUILD_DIR`: with `use_frameworks!` CocoaPods copies vendored
# xcframeworks into the pod target's own build dir, so for Runner that variable
# expands to a file nothing ever produces and Xcode fails on the missing input.
OPUS_XCFRAMEWORK = 'ogg_opus_player/darwin/Frameworks/libopus.xcframework'.freeze
OPUS_LIB_VAR = 'KOMET_OPUS_LIB'.freeze
OPUS_FORCE_LOAD = %(-force_load "$(#{OPUS_LIB_VAR})").freeze
OPUS_XCFRAMEWORK_DIR =
  File.expand_path(File.join('.symlinks', 'plugins', OPUS_XCFRAMEWORK), __dir__).freeze

def opus_slice(simulator)
  slice = Dir.glob(File.join(OPUS_XCFRAMEWORK_DIR, 'ios-*')).find do |dir|
    name = File.basename(dir)
    next false if name.include?('maccatalyst')
    next false unless File.exist?(File.join(dir, 'libopus.a'))

    name.end_with?('-simulator') == simulator
  end
  kind = simulator ? 'simulator' : 'device'
  raise "libopus.xcframework has no ios #{kind} slice in #{OPUS_XCFRAMEWORK_DIR}" if slice.nil?

  File.basename(slice)
end

# permission_handler compiles every permission handler unless told otherwise;
# the unused ones reference APIs that make App Store review ask for usage
# descriptions the app has no reason to declare.
PERMISSION_MACROS = %w[
  PERMISSION_CAMERA=1
  PERMISSION_MICROPHONE=1
  PERMISSION_PHOTOS=1
  PERMISSION_PHOTOS_ADD_ONLY=1
  PERMISSION_LOCATION=1
  PERMISSION_LOCATION_WHENINUSE=1
  PERMISSION_CONTACTS=1
  PERMISSION_NOTIFICATIONS=1
  PERMISSION_LOCATION_ALWAYS=0
  PERMISSION_MEDIA_LIBRARY=0
  PERMISSION_EVENTS=0
  PERMISSION_EVENTS_FULL_ACCESS=0
  PERMISSION_REMINDERS=0
  PERMISSION_SPEECH_RECOGNIZER=0
  PERMISSION_SENSORS=0
  PERMISSION_BLUETOOTH=0
  PERMISSION_APP_TRACKING_TRANSPARENCY=0
  PERMISSION_CRITICAL_ALERTS=0
  PERMISSION_ASSISTANT=0
].freeze

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)

    next unless target.name == 'permission_handler_apple'

    target.build_configurations.each do |config|
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] =
        ['$(inherited)'] + PERMISSION_MACROS
    end
  end

  opus_xcframework = "$(SRCROOT)/.symlinks/plugins/#{OPUS_XCFRAMEWORK}"
  opus_device_lib = "#{opus_xcframework}/#{opus_slice(false)}/libopus.a"
  opus_simulator_lib = "#{opus_xcframework}/#{opus_slice(true)}/libopus.a"

  installer.aggregate_targets.each do |target|
    next unless target.name == 'Pods-Runner'

    %w[debug profile release].each do |name|
      xcconfig = target.xcconfig_path(name)
      next unless File.exist?(xcconfig)

      contents = File.read(xcconfig)
      next if contents.include?(OPUS_LIB_VAR)

      contents += "\n" unless contents.end_with?("\n")
      contents += "#{OPUS_LIB_VAR}[sdk=iphoneos*] = #{opus_device_lib}\n"
      contents += "#{OPUS_LIB_VAR}[sdk=iphonesimulator*] = #{opus_simulator_lib}\n"

      if contents =~ /^OTHER_LDFLAGS = .*$/
        contents = contents.sub(/^OTHER_LDFLAGS = (.*)$/) do
          "OTHER_LDFLAGS = #{Regexp.last_match(1)} #{OPUS_FORCE_LOAD}"
        end
      else
        contents += "OTHER_LDFLAGS = $(inherited) #{OPUS_FORCE_LOAD}\n"
      end
      File.write(xcconfig, contents)
    end
  end
end
