Pod::Spec.new do |s|
  s.name             = 'tsnet_flutter'
  s.version          = '0.1.1'
  s.summary          = 'Embedded Tailscale tsnet for Flutter'
  s.description      = <<-DESC
Embed Tailscale's tsnet in Flutter apps. Provides a userspace WireGuard
tunnel with a localhost TCP proxy. Built with go build -buildmode=c-archive.
No VPN entitlement needed — uses userspace netstack.
                       DESC
  s.homepage         = 'https://github.com/svrnty/tsnet_flutter'
  s.license          = { :type => 'BSD-3-Clause', :file => '../LICENSE' }
  s.author           = { 'Svrnty' => 'mathias@svrnty.io' }
  s.source           = { :path => '.' }
  s.source_files     = 'Classes/**/*.{swift,h}'
  s.public_header_files = 'Classes/**/*.h'
  s.preserve_paths   = 'TailscaleKit.xcframework'
  s.dependency 'Flutter'
  s.platform         = :ios, '14.0'
  s.swift_version    = '5.0'

  s.libraries        = 'resolv'

  s.pod_target_xcconfig = {
    'DEFINES_MODULE' => 'YES',
    'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386 x86_64',
    # Link the Go static library — the script phase copies the correct slice
    # to DERIVED_FILE_DIR which is always writable and available at link time.
    'OTHER_LDFLAGS' => '$(inherited) -force_load "$(DERIVED_FILE_DIR)/TailscaleKit"',
  }

  s.user_target_xcconfig = {
    'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386 x86_64',
  }

  # Copy the correct xcframework slice to DERIVED_FILE_DIR before compile.
  # DERIVED_FILE_DIR is writable and exists before the link phase.
  s.script_phase = {
    :name => 'Select TailscaleKit Slice',
    :script => <<-'SCRIPT',
      XCFW="${PODS_TARGET_SRCROOT}/TailscaleKit.xcframework"

      if [ "$PLATFORM_NAME" = "iphonesimulator" ]; then
        SLICE="ios-arm64-simulator"
      else
        SLICE="ios-arm64"
      fi

      SRC="$XCFW/$SLICE/TailscaleKit.framework/TailscaleKit"
      DEST="${DERIVED_FILE_DIR}/TailscaleKit"

      if [ ! -f "$DEST" ] || [ "$SRC" -nt "$DEST" ]; then
        cp "$SRC" "$DEST"
        echo "Copied TailscaleKit ($SLICE) to $DEST"
      else
        echo "TailscaleKit ($SLICE) up to date"
      fi
    SCRIPT
    :execution_position => :before_compile,
    :output_files => ['$(DERIVED_FILE_DIR)/TailscaleKit'],
  }
end
