require_relative '../../node_modules/@capacitor/ios/scripts/pods_helpers'

platform :ios, '13.0'
# Static linkage helps isolate SQLCipher from Apple's system SQLite module/headers.
use_frameworks! :linkage => :static

# workaround to avoid Xcode caching of Pods that requires
# Product -> Clean Build Folder after new Cordova plugins installed
# Requires CocoaPods 1.6 or newer
install! 'cocoapods', :disable_input_output_paths => true

def capacitor_pods
  pod 'Capacitor', :path => '../../node_modules/@capacitor/ios'
  pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios'
  pod 'CapacitorCommunitySqlite', :path => '../../node_modules/@capacitor-community/sqlite'
  pod 'CapacitorMlkitBarcodeScanning', :path => '../../node_modules/@capacitor-mlkit/barcode-scanning'
  pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app'
  pod 'CapacitorCamera', :path => '../../node_modules/@capacitor/camera'
  pod 'CapacitorClipboard', :path => '../../node_modules/@capacitor/clipboard'
  pod 'CapacitorFilesystem', :path => '../../node_modules/@capacitor/filesystem'
  pod 'CapacitorPushNotifications', :path => '../../node_modules/@capacitor/push-notifications'
  pod 'CapacitorShare', :path => '../../node_modules/@capacitor/share'
  pod 'CapacitorStatusBar', :path => '../../node_modules/@capacitor/status-bar'
  pod 'CapawesomeCapacitorFilePicker', :path => '../../node_modules/@capawesome/capacitor-file-picker'
  pod 'TimesafariDailyNotificationPlugin', :path => '../../node_modules/@timesafari/daily-notification-plugin'
end

target 'App' do
  capacitor_pods
  # Add your Pods here
end

def merge_sqlite_omit_load_extension_definition(config)
  defs = config.build_settings['GCC_PREPROCESSOR_DEFINITIONS']
  if defs.nil?
    config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = ['$(inherited)', 'SQLITE_OMIT_LOAD_EXTENSION']
  elsif defs.is_a?(Array)
    unless defs.any? { |d| d.to_s.include?('SQLITE_OMIT_LOAD_EXTENSION') }
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = defs + ['SQLITE_OMIT_LOAD_EXTENSION']
    end
  else
    s = defs.to_s
    unless s.include?('SQLITE_OMIT_LOAD_EXTENSION')
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "#{s} SQLITE_OMIT_LOAD_EXTENSION".squeeze(' ').strip
    end
  end
end

def strip_system_sqlite_from_pod_config(config)
  bad_header = lambda do |path|
    p = path.to_s
    p.include?('/usr/include') || p.include?('/usr/local/include')
  end
  %w[HEADER_SEARCH_PATHS USER_HEADER_SEARCH_PATHS].each do |key|
    paths = config.build_settings[key]
    next unless paths
    if paths.is_a?(Array)
      config.build_settings[key] = paths.reject(&bad_header)
    else
      kept = paths.to_s.split(/\s+/).reject(&bad_header)
      config.build_settings[key] = kept.join(' ')
    end
  end
  %w[OTHER_LDFLAGS OTHER_LIBTOOLFLAGS].each do |key|
    val = config.build_settings[key]
    next unless val
    if val.is_a?(Array)
      config.build_settings[key] = val.reject do |x|
        s = x.to_s
        s.match?(/libsqlite3\.tbd/) || s == '-l"sqlite3"' || s.match?(/-l\s*sqlite3\b/)
      end
    else
      s = val.to_s.gsub(/\s*-l"sqlite3"\s+/, ' ')
           .gsub(/\s*-l\s*sqlite3\b/, ' ')
           .gsub(/[^\s]*libsqlite3\.tbd[^\s]*/, ' ')
      config.build_settings[key] = s.squeeze(' ').strip
    end
  end
end

post_install do |installer|
  assertDeploymentTarget(installer)
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64'
      config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
      merge_sqlite_omit_load_extension_definition(config)
      strip_system_sqlite_from_pod_config(config)
    end
  end
end

# Aggregate Pods-App xcconfigs merge -l"sqlite3" from dependencies; that pulls in Apple's
# libsqlite3 alongside SQLCipher. Strip it after CocoaPods writes the files (post_install is too early).
# Also strip SQLCipher header-guard macros leaked into GCC_PREPROCESSOR_DEFINITIONS: Swift explicit
# modules build the SDK SQLite3.modulemap PCM with the same -D flags; _SQLITE3_H_=1 empties sqlite3.h
# and breaks sqlite3ext.h (unknown sqlite3_* types).
def strip_aggregate_pods_app_xcconfig(contents)
  # Unlink system libsqlite3 (SQLCipher is the only SQLite).
  patched = contents.gsub(/\s+-l"sqlite3"\s+/, ' ')
                    .gsub(/\s+-lsqlite3\b/, ' ')
  # SQLCipher leaks sqlite3*.h guard macros into GCC_PREPROCESSOR_DEFINITIONS; Swift explicit
  # modules must not inherit them when building the SDK SQLite3 module.
  %w[_SQLITE3_H_=1 _FTS5_H=1 _SQLITE3RTREE_H_=1].each do |macro|
    escaped = Regexp.escape(macro)
    patched.gsub!(/(?:^|\s)-D#{escaped}(?=\s|$)/, ' ')
    patched.gsub!(/(?:^|\s)#{escaped}(?=\s|$)/, ' ')
  end
  patched.gsub(/[ \t]+/, ' ')
end

post_integrate do |installer|
  support = File.join(installer.sandbox.root, 'Target Support Files', 'Pods-App')
  %w[Pods-App.debug.xcconfig Pods-App.release.xcconfig].each do |name|
    path = File.join(support, name)
    next unless File.exist?(path)
    contents = File.read(path)
    patched = strip_aggregate_pods_app_xcconfig(contents)
    File.write(path, patched) if patched != contents
  end
end
