mdflib-sys 0.2.1

Low-level FFI bindings for mdflib
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Default library directories to check for static archives when pkg-config
/// doesn't report any `-L` paths (i.e. the libs are in the system default).
const DEFAULT_LIB_DIRS: &[&str] = &["/usr/lib", "/usr/lib64"];

fn main() {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());

    // Handle linking strategy based on features
    if cfg!(feature = "bundled") {
        build_bundled(&out_dir, &manifest_dir);
    } else if cfg!(feature = "system") {
        setup_system_linking(&manifest_dir);
    } else {
        panic!("Either 'bundled' or 'system' feature must be enabled");
    }

    // Generate bindings
    generate_bindings(&manifest_dir, &out_dir);

    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=bundled");
    println!("cargo:rerun-if-changed=src/mdf_c_wrapper.h");
    println!("cargo:rerun-if-changed=src/mdf_c_wrapper.cpp");
    println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
    println!("cargo:rerun-if-env-changed=VCPKG_DEFAULT_TRIPLET");
    println!("cargo:rerun-if-env-changed=CMAKE_GENERATOR");
}

fn is_msvc() -> bool {
    cfg!(target_os = "windows") && cfg!(target_env = "msvc")
}

/// Check whether the Cargo TARGET (not the host) uses musl libc.
/// Uses `CARGO_CFG_TARGET_ENV` because `cfg!()` in build scripts checks the
/// host, which is wrong when cross-compiling from glibc → musl.
fn is_musl() -> bool {
    env::var("CARGO_CFG_TARGET_ENV").is_ok_and(|v| v == "musl")
}

/// Returns (vcpkg_root, triplet) if VCPKG_ROOT is set and exists.
/// Default triplet is `x64-windows-static-md` (static libs, dynamic CRT) to match
/// Rust's default MSVC CRT linkage. Override with `VCPKG_DEFAULT_TRIPLET` env var.
fn get_vcpkg_config() -> Option<(PathBuf, String)> {
    let vcpkg_root = PathBuf::from(env::var("VCPKG_ROOT").ok()?);
    if !vcpkg_root.exists() {
        return None;
    }

    let triplet = env::var("VCPKG_DEFAULT_TRIPLET").unwrap_or_else(|_| {
        let arch = if cfg!(target_arch = "x86_64") {
            "x64"
        } else {
            "x86"
        };
        format!("{arch}-windows-static-md")
    });

    Some((vcpkg_root, triplet))
}

/// Search the vcpkg lib directory for a library whose name contains `base_name`
/// (case-insensitive). Returns the stem (filename without `.lib`) if found.
/// This handles vcpkg's CRT-suffix naming, e.g. `libexpatMD.lib` for the
/// `x64-windows-static-md` triplet.
fn find_vcpkg_lib(base_name: &str) -> Option<String> {
    let (vcpkg_root, triplet) = get_vcpkg_config()?;
    let lib_dir = vcpkg_root.join("installed").join(&triplet).join("lib");
    let lower = base_name.to_lowercase();
    for entry in std::fs::read_dir(&lib_dir).ok()? {
        let entry = entry.ok()?;
        let fname = entry.file_name();
        let name = fname.to_string_lossy();
        if name.to_lowercase().contains(&lower) && name.ends_with(".lib") {
            return Some(name.trim_end_matches(".lib").to_string());
        }
    }
    None
}

/// Apply platform-appropriate C++ compiler flags to a cc::Build.
fn apply_cpp_flags(build: &mut cc::Build) {
    if is_msvc() {
        build
            .flag("/std:c++17")
            .define("_SILENCE_ALL_CXX17_DEPRECATION_WARNINGS", None)
            .define("_CRT_SECURE_NO_WARNINGS", None);
    } else {
        build.flag("-std=c++17").flag("-Wno-overloaded-virtual");
    }
}

/// Apply all `*.patch` files from `mdflib-sys/patches/` to the bundled source
/// tree. Uses `git apply` if available, otherwise falls back to `patch -p1`.
/// Already-applied patches are skipped, making repeated builds idempotent.
fn apply_patches(manifest_dir: &Path, bundled_dir: &Path) {
    let patches_dir = manifest_dir.join("patches");
    if !patches_dir.exists() {
        return;
    }
    let mut patches: Vec<_> = std::fs::read_dir(&patches_dir)
        .expect("Failed to read patches directory")
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|p| p.extension().is_some_and(|ext| ext == "patch"))
        .collect();
    patches.sort();

    for patch in &patches {
        if try_apply_patch(bundled_dir, patch) {
            println!(
                "Applied patch: {}",
                patch.file_name().unwrap().to_string_lossy()
            );
        }
    }

    // Rebuild if patches change
    println!("cargo:rerun-if-changed={}", patches_dir.display());
    for patch in &patches {
        println!("cargo:rerun-if-changed={}", patch.display());
    }
}

/// Try to apply a single patch file. Returns true if newly applied, false if
/// already applied. Panics on failure.
fn try_apply_patch(bundled_dir: &Path, patch: &Path) -> bool {
    // Try git apply first (available when building from a git checkout)
    if let Ok(output) = Command::new("git")
        .current_dir(bundled_dir)
        .args(["apply", "--check", "--reverse"])
        .arg(patch)
        .output()
    {
        if output.status.success() {
            return false; // already applied
        }
        // Not yet applied — try to apply
        let apply = Command::new("git")
            .current_dir(bundled_dir)
            .args(["apply"])
            .arg(patch)
            .output()
            .expect("Failed to run git apply");
        if apply.status.success() {
            return true;
        }
        // git apply failed — fall through to `patch` command
    }

    // Fall back to the `patch` utility (e.g. in Docker / Alpine)
    if let Ok(output) = Command::new("patch")
        .current_dir(bundled_dir)
        .args(["-p1", "--forward", "-s"])
        .stdin(std::fs::File::open(patch).expect("Failed to open patch file"))
        .output()
    {
        if output.status.success() {
            return true;
        }
        // Exit code 1 with --forward means already applied
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        if stderr.contains("Reversed (or previously applied)")
            || stdout.contains("Reversed (or previously applied)")
        {
            return false;
        }
        panic!(
            "Failed to apply patch {}:\n{}{}",
            patch.display(),
            stdout,
            stderr,
        );
    }

    panic!(
        "Neither `git` nor `patch` found. Cannot apply {}",
        patch.display()
    );
}

fn build_bundled(out_dir: &Path, manifest_dir: &Path) {
    let bundled_dir = manifest_dir.join("bundled");
    let build_dir = out_dir.join("build");
    let install_dir = out_dir.join("install");

    // Create build directory
    std::fs::create_dir_all(&build_dir).expect("Failed to create build directory");
    std::fs::create_dir_all(&install_dir).expect("Failed to create install directory");

    // Check if we have the mdflib source
    if !bundled_dir.exists() {
        panic!(
            "Bundled mdflib source not found at {}. \
            Please run: git submodule update --init --recursive \
            or download mdflib source to the bundled/ directory",
            bundled_dir.display()
        );
    }

    // Apply patches from mdflib-sys/patches/ to the bundled source.
    apply_patches(manifest_dir, &bundled_dir);

    // Configure with CMake
    let mut cmake_config = Command::new("cmake");
    cmake_config
        .current_dir(&build_dir)
        .arg(&bundled_dir)
        .arg(format!("-DCMAKE_INSTALL_PREFIX={}", install_dir.display()))
        .arg("-DCMAKE_BUILD_TYPE=Release")
        .arg("-DBUILD_SHARED_LIBS=OFF")
        .arg("-DMDF_BUILD_SHARED_LIB=OFF")
        .arg("-DMDF_BUILD_SHARED_LIB_NET=OFF")
        .arg("-DMDF_BUILD_TEST=OFF")
        .arg("-DMDF_BUILD_DOC=OFF")
        .arg("-DMDF_BUILD_TOOLS=OFF")
        .arg("-DCMAKE_CXX_STANDARD=17");

    // Platform-specific CMake settings
    if is_msvc() {
        // Don't hardcode a Visual Studio version — let CMake auto-detect the
        // installed version. The -A flag is only valid for VS generators, so
        // skip it when the user has overridden CMAKE_GENERATOR to something
        // else (e.g. Ninja).
        if env::var("CMAKE_GENERATOR").map_or(true, |g| g.contains("Visual Studio")) {
            if cfg!(target_arch = "x86_64") {
                cmake_config.arg("-A").arg("x64");
            } else if cfg!(target_arch = "x86") {
                cmake_config.arg("-A").arg("Win32");
            }
        }

        // Use vcpkg toolchain if available for automatic dependency resolution
        if let Some((vcpkg_root, triplet)) = get_vcpkg_config() {
            let toolchain = vcpkg_root.join("scripts/buildsystems/vcpkg.cmake");
            if toolchain.exists() {
                cmake_config.arg(format!("-DCMAKE_TOOLCHAIN_FILE={}", toolchain.display()));
                cmake_config.arg(format!("-DVCPKG_TARGET_TRIPLET={triplet}"));
                // Use pre-installed packages rather than manifest mode so that
                // the bundled vcpkg.json doesn't trigger a redundant install.
                cmake_config.arg("-DVCPKG_MANIFEST_MODE=OFF");
            }
        }
    } else {
        cmake_config.arg("-G").arg("Unix Makefiles");

        // Pass the compilers detected by the cc crate to CMake so it uses the
        // same toolchain — essential for musl targets where CC is musl-gcc.
        let cc_tool = cc::Build::new().cargo_metadata(false).get_compiler();
        let cxx_tool = cc::Build::new()
            .cpp(true)
            .cargo_metadata(false)
            .get_compiler();
        cmake_config.arg(format!("-DCMAKE_C_COMPILER={}", cc_tool.path().display()));
        cmake_config.arg(format!(
            "-DCMAKE_CXX_COMPILER={}",
            cxx_tool.path().display()
        ));
    }

    // Help CMake find dependencies
    add_dependency_hints(&mut cmake_config);

    // Run CMake configure
    let cmake_output = cmake_config
        .output()
        .expect("Failed to run CMake configure");
    if !cmake_output.status.success() {
        eprintln!("CMake configure failed:");
        eprintln!("stdout: {}", String::from_utf8_lossy(&cmake_output.stdout));
        eprintln!("stderr: {}", String::from_utf8_lossy(&cmake_output.stderr));
        panic_with_dependency_errors(&String::from_utf8_lossy(&cmake_output.stderr));
    }

    // Run CMake build and install
    let mut cmake_build = Command::new("cmake");
    cmake_build
        .current_dir(&build_dir)
        .arg("--build")
        .arg(".")
        .arg("--config")
        .arg("Release")
        .arg("--target")
        .arg("install");

    if let Ok(jobs) = env::var("NUM_JOBS") {
        cmake_build.arg("--parallel").arg(jobs);
    } else if let Ok(jobs) = std::thread::available_parallelism() {
        cmake_build.arg("--parallel").arg(jobs.get().to_string());
    }

    let build_output = cmake_build.output().expect("Failed to run CMake build");
    if !build_output.status.success() {
        panic!(
            "CMake build failed:\nstdout: {}\nstderr: {}",
            String::from_utf8_lossy(&build_output.stdout),
            String::from_utf8_lossy(&build_output.stderr)
        );
    }

    // Build the C wrapper
    let mut cc_build = cc::Build::new();
    cc_build
        .cpp(true)
        .file("src/mdf_c_wrapper.cpp")
        .include(install_dir.join("include"))
        .include(bundled_dir.join("include"));

    // On Windows, mdflib's CMake installs headers to <prefix>/mdf/include/
    let mdf_include = install_dir.join("mdf").join("include");
    if mdf_include.exists() {
        cc_build.include(&mdf_include);
    }

    apply_cpp_flags(&mut cc_build);

    // On MSVC with vcpkg, add vcpkg include path for dependency headers
    if is_msvc() {
        if let Some((vcpkg_root, triplet)) = get_vcpkg_config() {
            let vcpkg_include = vcpkg_root.join("installed").join(&triplet).join("include");
            if vcpkg_include.exists() {
                cc_build.include(&vcpkg_include);
            }
        }
    }

    cc_build.compile("mdf_c_wrapper");

    // Set up linking
    setup_bundled_linking(&install_dir);
}

fn setup_dependencies() {
    println!("cargo:rerun-if-env-changed=PKG_CONFIG_PATH");
    if is_msvc() {
        // On MSVC, vcpkg library names may carry a CRT-linkage suffix.
        // e.g. expat → libexpatMD.lib (dynamic CRT) or libexpatMT.lib (static CRT).
        let zlib_name = find_vcpkg_lib("zlib").unwrap_or_else(|| "zlib".to_string());
        let expat_name = find_vcpkg_lib("expat").unwrap_or_else(|| "libexpat".to_string());
        setup_dependency("zlib", &zlib_name);
        setup_dependency("expat", &expat_name);
    } else {
        setup_dependency("zlib", "z");
        setup_dependency("expat", "expat");
    }
}

fn setup_dependency(name: &str, fallback_name: &str) {
    // Add /usr/lib/${target} to default dirs
    let default_lib_dirs = if let Ok(target) = env::var("TARGET") {
        let mut dirs = vec![format!("/usr/lib/{target}")];
        dirs.extend(DEFAULT_LIB_DIRS.iter().map(|s| s.to_string()));
        dirs
    } else {
        DEFAULT_LIB_DIRS.iter().map(|s| s.to_string()).collect()
    };
    let upper_name = name.to_uppercase();
    println!("cargo:rerun-if-env-changed={upper_name}_LIBRARY");
    println!("cargo:rerun-if-env-changed={upper_name}_INCLUDE_DIR");
    println!("cargo:rerun-if-env-changed={upper_name}_NO_PKG_CONFIG");

    // Explicit environment variable path — always preferred
    if let Ok(lib_path_str) = env::var(format!("{upper_name}_LIBRARY")) {
        println!("Found {name} via {upper_name}_LIBRARY environment variable");
        let lib_path = PathBuf::from(&lib_path_str);
        if let Some(lib_dir) = lib_path.parent() {
            println!("cargo:rustc-link-search=native={}", lib_dir.display());
        }
        if let Some(lib_name) = lib_path.file_stem() {
            let lib_name_str = lib_name.to_string_lossy();
            let clean_name = lib_name_str.strip_prefix("lib").unwrap_or(&lib_name_str);
            println!("cargo:rustc-link-lib={clean_name}");
        }
        return;
    }

    // Try pkg-config to find library search paths, then prefer static (.a) but fall back to dynamic (.so) if the static archive doesn't exist.
    let mut pkg = pkg_config::Config::new();
    pkg.statik(true);

    if let Ok(lib) = pkg.probe(name) {
        println!("Found {name} via pkg-config");
        for dir in &lib.link_paths {
            println!("cargo:rustc-link-search=native={}", dir.display());
        }
        // Check pkg-config paths and default system dirs for a static archive
        let static_name = format!("lib{fallback_name}.a");
        let search_dirs: Vec<&Path> = lib
            .link_paths
            .iter()
            .map(|p| p.as_path())
            .chain(default_lib_dirs.iter().map(Path::new))
            .collect();
        let has_static = search_dirs.iter().any(|d| d.join(&static_name).exists());
        if has_static {
            println!("cargo:rustc-link-lib=static={fallback_name}");
        } else {
            println!("cargo:rustc-link-lib=dylib={fallback_name}");
        }
        return;
    }

    // Fallback to default system linking (dylib — let the linker decide)
    println!(
        "cargo:warning={name} not found via pkg-config or environment variables, using system defaults"
    );
    println!("cargo:rustc-link-lib={fallback_name}");
}

fn add_dependency_hints(cmake_config: &mut Command) {
    add_single_dependency_hint(cmake_config, "ZLIB");
    add_single_dependency_hint(cmake_config, "EXPAT");

    if env::var("ZLIB_LIBRARY").is_err() && env::var("EXPAT_LIBRARY").is_err() {
        add_platform_dependency_hints(cmake_config);
    }
}

fn add_single_dependency_hint(cmake_config: &mut Command, name: &str) {
    if let Ok(lib_path_str) = env::var(format!("{name}_LIBRARY")) {
        let lib_path = PathBuf::from(&lib_path_str);
        if let Some(lib_dir) = lib_path.parent() {
            if let Some(root_dir) = lib_dir.parent() {
                cmake_config.arg(format!("-D{}_ROOT={}", name, root_dir.display()));
            }
        }
        cmake_config.arg(format!("-D{name}_LIBRARY={lib_path_str}"));
    }
    if let Ok(include_path) = env::var(format!("{name}_INCLUDE_DIR")) {
        cmake_config.arg(format!("-D{name}_INCLUDE_DIR={include_path}"));
    }
}

fn add_platform_dependency_hints(cmake_config: &mut Command) {
    if cfg!(target_os = "macos") {
        if Path::new("/opt/homebrew/opt/zlib").exists() {
            cmake_config.arg("-DZLIB_ROOT=/opt/homebrew/opt");
            cmake_config.arg("-DZLIB_LIBRARY=/opt/homebrew/opt/zlib/lib/libz.a");
        }
        if Path::new("/opt/homebrew/opt/expat").exists() {
            cmake_config.arg("-DEXPAT_ROOT=/opt/homebrew/opt");
            cmake_config.arg("-DEXPAT_LIBRARY=/opt/homebrew/opt/expat/lib/libexpat.a");
        }
        if Path::new("/usr/include/zlib.h").exists() {
            cmake_config.arg("-DZLIB_ROOT=/usr");
        }
        if Path::new("/usr/include/expat.h").exists() {
            cmake_config.arg("-DEXPAT_ROOT=/usr");
        }
    } else if cfg!(target_os = "linux") {
        if is_musl() {
            // For musl builds, we must NOT set ZLIB_ROOT=/usr or EXPAT_ROOT=/usr
            // because that causes CMake to add -I/usr/include to the compiler
            // flags, which pulls in glibc headers (e.g. features-time64.h →
            // bits/wordsize.h) that don't exist in the musl sysroot and conflict
            // with the musl-g++ wrapper's carefully crafted -isystem paths.
            //
            // Instead, set explicit INCLUDE_DIR and LIBRARY paths so CMake never
            // adds /usr/include to the search path.
            let search_dirs = musl_lib_search_dirs();
            if let Some(inc) = musl_include_dir() {
                cmake_config.arg(format!("-DZLIB_INCLUDE_DIR={inc}"));
                cmake_config.arg(format!("-DEXPAT_INCLUDE_DIR={inc}"));
            }
            for lib_dir in &search_dirs {
                let zlib = format!("{lib_dir}/libz.a");
                if Path::new(&zlib).exists() {
                    cmake_config.arg(format!("-DZLIB_LIBRARY={zlib}"));
                    break;
                }
            }
            for lib_dir in &search_dirs {
                let expat = format!("{lib_dir}/libexpat.a");
                if Path::new(&expat).exists() {
                    cmake_config.arg(format!("-DEXPAT_LIBRARY={expat}"));
                    break;
                }
            }
        } else {
            // Arch linux and some other distros put zlib and expat in /usr/
            if Path::new("/usr/include/zlib.h").exists() {
                cmake_config.arg("-DZLIB_ROOT=/usr");
            }
            if Path::new("/usr/include/expat.h").exists() {
                cmake_config.arg("-DEXPAT_ROOT=/usr");
            }
            if Path::new("/usr/lib/libexpat.a").exists() {
                cmake_config.arg("-DEXPAT_LIBRARY=/usr/lib/libexpat.a");
            } else if Path::new("/usr/lib/libexpat.so").exists() {
                cmake_config.arg("-DEXPAT_LIBRARY=/usr/lib/libexpat.so");
            }
            if Path::new("/usr/lib/libz.a").exists() {
                cmake_config.arg("-DZLIB_LIBRARY=/usr/lib/libz.a");
            } else if Path::new("/usr/lib/libz.so").exists() {
                cmake_config.arg("-DZLIB_LIBRARY=/usr/lib/libz.so");
            }
        }
    }
}

/// Return candidate library directories for musl targets, ordered by preference.
fn musl_lib_search_dirs() -> Vec<String> {
    let mut dirs = Vec::new();
    // Architecture-specific musl sysroot (e.g. /usr/lib/x86_64-linux-musl)
    if let Ok(target) = env::var("TARGET") {
        if let Some(arch) = target.split('-').next() {
            let musl_dir = format!("/usr/lib/{arch}-linux-musl");
            if Path::new(&musl_dir).exists() {
                dirs.push(musl_dir);
            }
        }
    }
    // GNU multiarch dir (static .a files from -dev packages work with musl)
    for dir in &["/usr/lib/x86_64-linux-gnu", "/usr/lib"] {
        if Path::new(dir).exists() {
            dirs.push(dir.to_string());
        }
    }
    dirs
}

/// Return the musl include directory (e.g. /usr/include/x86_64-linux-musl)
/// where library headers (zlib.h, expat.h) should be found without pulling in
/// glibc system headers from /usr/include.
fn musl_include_dir() -> Option<String> {
    if let Ok(target) = env::var("TARGET") {
        if let Some(arch) = target.split('-').next() {
            let musl_dir = format!("/usr/include/{arch}-linux-musl");
            if Path::new(&musl_dir).exists() {
                return Some(musl_dir);
            }
        }
    }
    None
}

/// Add the GCC library directory to the linker search path so that
/// `libstdc++.a` (and `libgcc.a` / `libgcc_eh.a`) can be found when
/// statically linking C++ code on musl targets.
fn add_gcc_lib_search_path() {
    if let Ok(output) = Command::new("g++")
        .arg("-print-file-name=libstdc++.a")
        .output()
    {
        if output.status.success() {
            let path_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
            let path = Path::new(&path_str);
            if path.is_absolute() {
                if let Some(dir) = path.parent() {
                    println!("cargo:rustc-link-search=native={}", dir.display());
                }
            }
        }
    }
}

fn setup_bundled_linking(install_dir: &Path) {
    let lib_dir = install_dir.join("lib");
    if lib_dir.exists() {
        println!("cargo:rustc-link-search=native={}", lib_dir.display());
    }
    if install_dir.join("lib64").exists() {
        println!(
            "cargo:rustc-link-search=native={}",
            install_dir.join("lib64").display()
        );
    }

    // On Windows, mdflib's CMake installs to <prefix>/mdf/lib/ rather than
    // <prefix>/lib/. Add that path so the linker can find mdf.lib.
    let mdf_lib_dir = install_dir.join("mdf").join("lib");
    if mdf_lib_dir.exists() {
        println!("cargo:rustc-link-search=native={}", mdf_lib_dir.display());
    }

    // On Windows with vcpkg, add vcpkg lib directory so the linker can find
    // zlib.lib / libexpat.lib that were installed by vcpkg.
    if is_msvc() {
        if let Some((vcpkg_root, triplet)) = get_vcpkg_config() {
            let vcpkg_lib = vcpkg_root.join("installed").join(&triplet).join("lib");
            if vcpkg_lib.exists() {
                println!("cargo:rustc-link-search=native={}", vcpkg_lib.display());
            }
        }
    }

    // Link the static libraries in the correct order
    println!("cargo:rustc-link-lib=static=mdf_c_wrapper");
    println!("cargo:rustc-link-lib=static=mdf");

    // Link dependencies after the main libraries
    setup_dependencies();

    // Link platform-specific system libraries
    if cfg!(target_os = "windows") {
        println!("cargo:rustc-link-lib=dylib=user32");
        println!("cargo:rustc-link-lib=dylib=kernel32");
        println!("cargo:rustc-link-lib=dylib=ws2_32");
        println!("cargo:rustc-link-lib=dylib=advapi32");
        println!("cargo:rustc-link-lib=dylib=shell32");
        println!("cargo:rustc-link-lib=dylib=ole32");
    } else if cfg!(target_os = "linux") {
        if is_musl() {
            // For musl, link stdc++ statically for a self-contained binary.
            // m, pthread, and dl are part of musl's libc — no separate linking.
            println!("cargo:rustc-link-lib=static=stdc++");
            // Add the musl sysroot lib dir so the linker finds static .a files
            for dir in musl_lib_search_dirs() {
                println!("cargo:rustc-link-search=native={dir}");
            }
            // The musl-gcc specs may omit the GCC lib directory where
            // libstdc++.a lives. Ask g++ for the path and add it explicitly.
            add_gcc_lib_search_path();
        } else {
            println!("cargo:rustc-link-lib=dylib=stdc++");
            println!("cargo:rustc-link-lib=dylib=m");
            println!("cargo:rustc-link-lib=dylib=pthread");
            println!("cargo:rustc-link-lib=dylib=dl");
        }
    } else if cfg!(target_os = "macos") {
        println!("cargo:rustc-link-lib=dylib=c++");
        println!("cargo:rustc-link-lib=dylib=System");
        println!("cargo:rustc-link-lib=framework=Foundation");
    }
}

fn setup_system_linking(_manifest_dir: &Path) {
    let mut cc_build = cc::Build::new();
    cc_build.cpp(true).file("src/mdf_c_wrapper.cpp");
    apply_cpp_flags(&mut cc_build);

    // Try to find system-installed mdflib using pkg-config
    if let Ok(library) = pkg_config::Config::new()
        .atleast_version("2.3")
        .probe("mdflib")
    {
        for path in library.include_paths {
            cc_build.include(path);
        }
    } else {
        println!("cargo:warning=pkg-config failed for mdflib, trying manual discovery");
        println!("cargo:rustc-link-lib=mdf");

        // Link dependencies after the main library
        setup_dependencies();

        if cfg!(target_os = "linux") {
            if is_musl() {
                println!("cargo:rustc-link-lib=static=stdc++");
                for dir in musl_lib_search_dirs() {
                    println!("cargo:rustc-link-search=native={dir}");
                }
                add_gcc_lib_search_path();
            } else {
                println!("cargo:rustc-link-lib=dylib=stdc++");
                println!("cargo:rustc-link-lib=dylib=m");
                println!("cargo:rustc-link-lib=dylib=pthread");
                println!("cargo:rustc-link-lib=dylib=dl");
            }
            cc_build.include("/usr/local/include");
            cc_build.include("/usr/include");
        } else if cfg!(target_os = "macos") {
            println!("cargo:rustc-link-lib=dylib=c++");
            println!("cargo:rustc-link-lib=dylib=System");
            println!("cargo:rustc-link-lib=framework=Foundation");
            cc_build.include("/usr/local/include");
            cc_build.include("/opt/homebrew/include");
        } else if cfg!(target_os = "windows") {
            println!("cargo:rustc-link-lib=dylib=user32");
            println!("cargo:rustc-link-lib=dylib=kernel32");
            println!("cargo:rustc-link-lib=dylib=ws2_32");
            println!("cargo:rustc-link-lib=dylib=advapi32");
            println!("cargo:rustc-link-lib=dylib=shell32");
            println!("cargo:rustc-link-lib=dylib=ole32");
            cc_build.include("C:/Program Files/mdflib/include");

            // Add vcpkg include/lib paths if available
            if let Some((vcpkg_root, triplet)) = get_vcpkg_config() {
                let vcpkg_include = vcpkg_root.join("installed").join(&triplet).join("include");
                let vcpkg_lib = vcpkg_root.join("installed").join(&triplet).join("lib");
                if vcpkg_include.exists() {
                    cc_build.include(&vcpkg_include);
                }
                if vcpkg_lib.exists() {
                    println!("cargo:rustc-link-search=native={}", vcpkg_lib.display());
                }
            }
        }
    }

    cc_build.compile("mdf_c_wrapper");
}

fn generate_bindings(manifest_dir: &Path, out_dir: &Path) {
    let wrapper_path = manifest_dir.join("src").join("mdf_c_wrapper.h");
    println!("Generating bindings from {}", wrapper_path.display());

    let mut bindgen_builder = bindgen::Builder::default()
        .header(wrapper_path.to_str().unwrap())
        .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
        .clang_arg("-xc++")
        .clang_arg("-std=c++17")
        .default_enum_style(bindgen::EnumVariation::Rust {
            non_exhaustive: true,
        })
        .blocklist_type("std::.*")
        .derive_debug(true)
        .derive_default(true)
        .derive_copy(true)
        .derive_eq(true)
        .derive_hash(true)
        .derive_ord(true)
        .derive_partialeq(true)
        .derive_partialord(true);

    // Add include paths for bindgen
    let bundled_include = manifest_dir.join("bundled").join("include");
    if bundled_include.exists() {
        bindgen_builder = bindgen_builder.clang_arg(format!("-I{}", bundled_include.display()));
    }
    if let Ok(install_dir) = env::var("OUT_DIR") {
        let include_path = PathBuf::from(install_dir).join("install/include");
        if include_path.exists() {
            bindgen_builder = bindgen_builder.clang_arg(format!("-I{}", include_path.display()));
        }
    }
    if let Ok(zlib_include) = env::var("ZLIB_INCLUDE_DIR") {
        bindgen_builder = bindgen_builder.clang_arg(format!("-I{zlib_include}"));
    }
    if let Ok(expat_include) = env::var("EXPAT_INCLUDE_DIR") {
        bindgen_builder = bindgen_builder.clang_arg(format!("-I{expat_include}"));
    }
    if cfg!(target_os = "macos") {
        if Path::new("/opt/homebrew/include").exists() {
            bindgen_builder = bindgen_builder.clang_arg("-I/opt/homebrew/include");
        }
        if let Ok(output) = Command::new("xcrun").args(["--show-sdk-path"]).output() {
            if output.status.success() {
                let sdk_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
                bindgen_builder = bindgen_builder.clang_arg(format!("-I{sdk_path}/usr/include"));
            }
        }
    }

    let bindings = bindgen_builder
        .generate()
        .expect("Unable to generate bindings");

    bindings
        .write_to_file(out_dir.join("bindings.rs"))
        .expect("Couldn't write bindings!");

    println!("Successfully generated bindings");
}

fn panic_with_dependency_errors(stderr: &str) {
    if stderr.contains("Could NOT find ZLIB") {
        eprintln!("\nzlib not found. Please install zlib development libraries:");
        print_install_instructions("zlib1g-dev", "zlib-devel");
    }
    if stderr.contains("Could NOT find EXPAT") {
        eprintln!("\nexpat not found. Please install expat development libraries:");
        print_install_instructions("libexpat1-dev", "expat-devel");
    }
    panic!("CMake configuration failed");
}

fn print_install_instructions(debian_pkg: &str, rhel_pkg: &str) {
    if cfg!(target_os = "linux") {
        eprintln!("  Ubuntu/Debian: sudo apt install {debian_pkg}");
        eprintln!("  CentOS/RHEL/Fedora: sudo dnf install {rhel_pkg}");
    }
    let name = rhel_pkg.split('-').next().unwrap_or("").to_uppercase();
    eprintln!("\nAlternatively, set environment variables:");
    eprintln!(
        "  {}_LIBRARY=/path/to/lib{}.so (or .a/.lib)",
        name,
        rhel_pkg.replace("-devel", "")
    );
    eprintln!(
        "  {}_INCLUDE_DIR=/path/to/{}/headers",
        name,
        rhel_pkg.replace("-devel", "")
    );
}