platform :osx, '10.15'

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

require 'fileutils'

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

def flutter_root
  generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', '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 Flutter-Generated.xcconfig, then run \"flutter pub get\""
end

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

flutter_macos_podfile_setup

def nim_core_v2_wrapper_plugin_root
  File.expand_path(File.join(__dir__, 'Flutter', 'ephemeral', '.symlinks', 'plugins', 'nim_core_v2_macos'))
end

def prepare_nim_core_v2_wrapper_libraries
  plugin_root = nim_core_v2_wrapper_plugin_root
  return unless Dir.exist?(plugin_root)

  wrapper_root = File.join(plugin_root, 'nim_sdk', 'wrapper')
  return unless Dir.exist?(wrapper_root)

  sdk_path = `xcrun --sdk macosx --show-sdk-path`.strip
  raise 'Failed to resolve macOS SDK path for nim_core_v2 wrapper build' if sdk_path.empty?

  wrapper_root_dir = File.expand_path(File.join(__dir__, 'Flutter', 'ephemeral', 'nim_core_v2_wrapper'))
  build_dir = File.join(wrapper_root_dir, 'build')
  lib_dir = File.join(wrapper_root_dir, 'lib')
  FileUtils.mkdir_p(lib_dir)

  cmake_args = [
    'cmake',
    '-S', wrapper_root,
    '-B', build_dir,
    '-G', 'Ninja',
    '-DINSTALL_CPP_WRAPPER=OFF',
    '-DBUILD_SHARED_LIBS=OFF',
    '-DCMAKE_CXX_STANDARD=14',
    '-DCMAKE_OSX_DEPLOYMENT_TARGET=10.15',
    '-DCMAKE_OSX_ARCHITECTURES=x86_64',
    "-DCMAKE_OSX_SYSROOT=#{sdk_path}",
  ]

  unless system({ 'CC' => 'clang', 'CXX' => 'clang++' }, *cmake_args)
    raise 'Failed to configure nim_core_v2 wrapper static libraries'
  end

  unless system('cmake', '--build', build_dir, '--config', 'Release', '--target', 'nim_cpp_wrapper', 'nim_wrapper_util', '-j', '4')
    raise 'Failed to build nim_core_v2 wrapper static libraries'
  end

  {
    'libnim_cpp_wrapper.a' => File.join(build_dir, 'nim_cpp_wrapper', 'libnim_cpp_wrapper.a'),
    'libnim_wrapper_util.a' => File.join(build_dir, 'nim_wrapper_util', 'libnim_wrapper_util.a'),
  }.each do |artifact, source|
    raise "Missing nim_core_v2 wrapper artifact: #{artifact}" unless File.exist?(source)

    FileUtils.cp(source, File.join(lib_dir, artifact))
  end
end

def enforce_macos_x86_64_only(project)
  project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ARCHS[sdk=macosx*]'] = 'x86_64'
      config.build_settings['EXCLUDED_ARCHS[sdk=macosx*]'] = 'arm64'
      config.build_settings['ONLY_ACTIVE_ARCH'] = 'YES'
    end
  end
  project.save
end

def append_xcconfig_value(content, key, value)
  return content if content.include?(value)

  pattern = /^#{Regexp.escape(key)} = (.+)$/
  if content.match?(pattern)
    content.sub(pattern) { |line| "#{line} #{value}" }
  else
    "#{content.rstrip}\n#{key} = $(inherited) #{value}\n"
  end
end

def patch_nim_core_v2_wrapper_linkage
  wrapper_lib_dir = '${PODS_ROOT}/../Flutter/ephemeral/nim_core_v2_wrapper/lib'

  Dir.glob(File.join(__dir__, 'Pods', 'Target Support Files', 'Pods-Runner', 'Pods-Runner*.xcconfig')).each do |path|
    content = File.read(path)
    content = append_xcconfig_value(content, 'LIBRARY_SEARCH_PATHS', '"$(NIM_CORE_V2_WRAPPER_LIB_DIR)"')
    content = append_xcconfig_value(content, 'OTHER_LDFLAGS', '-l"nim_cpp_wrapper" -l"nim_wrapper_util"')

    unless content.include?('NIM_CORE_V2_WRAPPER_LIB_DIR =')
      content = "#{content.rstrip}\nNIM_CORE_V2_WRAPPER_LIB_DIR = #{wrapper_lib_dir}\n"
    end

    File.write(path, content)
  end
end

target 'Runner' do
  use_frameworks!

  flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__))
  target 'RunnerTests' do
    inherit! :search_paths
  end
end

post_install do |installer|
  prepare_nim_core_v2_wrapper_libraries

  installer.pods_project.targets.each do |target|
    flutter_additional_macos_build_settings(target)
  end

  # Example-only workaround: this target also pulls in nim_core_v2_macos,
  # whose bundled yx_alog currently has no arm64 slice.
  enforce_macos_x86_64_only(installer.pods_project)

  user_projects = {}
  installer.aggregate_targets.each do |aggregate_target|
    user_project = aggregate_target.user_project
    next if user_project.nil?

    project_path = user_project.path.to_s
    next if user_projects[project_path]

    enforce_macos_x86_64_only(user_project)
    user_projects[project_path] = true
  end

  patch_nim_core_v2_wrapper_linkage
end
