cp2k-sys 0.3.1

Builds CP2K and its native dependencies (internal -sys crate for cp2k-rs)
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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
//! Build script for cp2k-sys
//!
//! Clones and builds CP2K from source together with all of its native
//! dependencies (FFTW3, ScaLAPACK, DBCSR, Libxc, libxsmm), then exports
//! their install paths as `cargo:` metadata. The parent crate (cp2k-rs) consumes
//! these via DEP_CP2K_* and emits the final link line, because
//! `cargo:rustc-link-arg` does not propagate from a dependency's build script.

use std::env;
use std::path::{Path, PathBuf};
use std::process::Command;

/// CP2K release branch to build. Bumping this invalidates any existing cached
/// checkout: `clone_cp2k_repository` wipes and re-clones a checkout whose
/// branch does not match (together with the stale CMake build dir).
const CP2K_GIT_BRANCH: &str = "support/v2026.2";

/// Pinned commit SHA on `CP2K_GIT_BRANCH`. The clone is reproducible only if
/// this SHA is verified after fetch; a branch is a moving pointer. If upstream
/// advances the branch, `clone_cp2k_repository` aborts the build until the pin
/// is consciously updated here.
const CP2K_GIT_COMMIT: &str = "67b5da876dd6a76b8b021d5a04d1c81ba79a4c50";

/// An upstream ref to build instead of the pinned release, e.g.
/// `CP2K_GIT_REF=master` for a nightly build against CP2K's development tip.
///
/// This deliberately gives up reproducibility: a branch is a moving pointer, so
/// the commit assertion below cannot apply and is skipped. Everything else about
/// the pinned build is untouched — in particular the checkout lives in its own
/// directory (see `upstream_dir_suffix`), because the staleness check wipes a
/// checkout whose HEAD does not match, and sharing one would make every switch
/// between the two destroy the other's tree and force a full CP2K rebuild.
fn cp2k_git_ref_override() -> Option<String> {
    env::var("CP2K_GIT_REF")
        .ok()
        .filter(|r| !r.trim().is_empty())
}

/// Directory suffix keeping an override build apart from the pinned one.
fn upstream_dir_suffix() -> String {
    match cp2k_git_ref_override() {
        // Slashes and dots would nest or hide the directory.
        Some(r) => format!(
            "-upstream-{}",
            r.chars()
                .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
                .collect::<String>()
        ),
        None => String::new(),
    }
}

// ── Target-architecture helpers ──────────────────────────────────────────────

/// Returns the target architecture identifier.
/// Set `CP2K_TARGET_ARCH=v4` to compile for x86-64-v4 (AVX-512).
/// Defaults to `"v3"` (x86-64-v3 = AVX2 / FMA / BMI2 / …).
fn cp2k_target_arch() -> String {
    env::var("CP2K_TARGET_ARCH").unwrap_or_else(|_| "v3".to_string())
}

/// Returns the `-march=` flag for the given architecture string.
fn march_flag(arch: &str) -> String {
    match arch {
        "v4" => "-march=x86-64-v4".to_string(),
        _ => "-march=x86-64-v3".to_string(),
    }
}

/// Returns the stable-directory suffix for the given architecture.
/// The v3 build uses bare names (no suffix) to stay backward-compatible
/// with existing caches.
fn arch_dir_suffix(arch: &str) -> &'static str {
    match arch {
        "v4" => "-v4",
        _ => "",
    }
}

/// `;<ROCm prefix>` for CMAKE_PREFIX_PATH under the `hip` feature (mirrors
/// `cp2k_build_utils::rocm_cmake_prefix_suffix`), so CMake finds rocblas etc.
fn rocm_cmake_prefix_suffix() -> String {
    if std::env::var("CARGO_FEATURE_HIP").is_ok() {
        format!(
            ";{}",
            std::env::var("ROCM_PATH").unwrap_or_else(|_| "/opt/rocm".into())
        )
    } else {
        String::new()
    }
}

/// GPU-variant suffix for the CP2K stable directory (mirrors
/// `cp2k_build_utils::gpu_dir_suffix`): CPU and GPU builds must not share a
/// cache, since the skip check only tests whether the built library exists.
fn gpu_dir_suffix() -> &'static str {
    if std::env::var("CARGO_FEATURE_CUDA").is_ok() {
        "-cuda"
    } else if std::env::var("CARGO_FEATURE_HIP").is_ok() {
        "-hip"
    } else {
        ""
    }
}

/// Skala-variant suffix for the CP2K stable directory. The Skala build compiles
/// CP2K against a GauXC that has ONEDFT (`GAUXC_HAS_ONEDFT`) enabled, which
/// changes `xc_gauxc_interface.F`; it must not reuse the default variant's
/// CP2K build tree (the skip check only tests whether libcp2k.a exists).
fn skala_dir_suffix() -> &'static str {
    if std::env::var("CARGO_FEATURE_SKALA").is_ok() {
        "-skala"
    } else {
        ""
    }
}

fn main() {
    // cp2k-sys builds CP2K and all of its native dependencies, then exports their
    // install paths as `cargo:` metadata. The parent crate (cp2k-rs) consumes these
    // via DEP_CP2K_* and assembles the final link line itself, because
    // `cargo:rustc-link-arg` directives do NOT propagate from a dependency's build
    // script to the crate that owns the cdylib / binary.
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-env-changed=CP2K_TARGET_ARCH");
    println!("cargo:rerun-if-env-changed=CP2K_GIT_REF");
    // GPU build settings are read below (CUDA_ARCH/HIP_ARCH/CUDA_PATH/ROCM_PATH);
    // without these directives a change in the environment would not trigger a
    // rebuild, leaving a stale GPU binary in the cache.
    println!("cargo:rerun-if-env-changed=CP2K_CUDA_ARCH");
    println!("cargo:rerun-if-env-changed=CP2K_HIP_ARCH");
    println!("cargo:rerun-if-env-changed=CUDA_PATH");
    println!("cargo:rerun-if-env-changed=ROCM_PATH");

    // GPU features are mutually exclusive.
    #[cfg(all(feature = "cuda", feature = "hip"))]
    compile_error!("The 'cuda' and 'hip' features are mutually exclusive. Enable only one.");

    // Watch for changes in the Fortran extensions.
    if cfg!(feature = "extended") {
        println!("cargo:rerun-if-changed=extensions/fortran/libcp2k_extended.F90");
        println!("cargo:rerun-if-changed=extensions/fortran/libcp2k_mpi.F90");
        println!("cargo:rerun-if-changed=extensions/include/libcp2k_extended.h");
    }

    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let mpi_base_dir = detect_mpi_installation();

    println!("cargo:warning=Building CP2K from source - this may take 30+ minutes");

    // Use stable paths (under target/<profile>/) so CP2K source and build survive
    // build.rs hash changes between rebuilds.
    // OUT_DIR = .../target/<profile>/build/cp2k-sys-<hash>/out/
    // ancestors: nth(0)=out, nth(1)=cp2k-sys-<hash>, nth(2)=build, nth(3)=<profile>
    let profile_dir = out_dir.ancestors().nth(3).unwrap_or(&out_dir).to_path_buf();
    let arch = cp2k_target_arch();
    // GPU variants must not share the cache with CPU builds.
    let cp2k_stable_dir = profile_dir.join(format!(
        "cp2k-stable{}{}{}{}",
        arch_dir_suffix(&arch),
        gpu_dir_suffix(),
        skala_dir_suffix(),
        upstream_dir_suffix()
    ));
    std::fs::create_dir_all(&cp2k_stable_dir).expect("Failed to create cp2k-stable dir");

    let cp2k_src_dir = clone_cp2k_repository(&cp2k_stable_dir);

    // Resolve static OpenBLAS location from the openblas-src build dependency.
    // openblas-src (links = "openblas") emits cargo:LIBRARY / cargo:INCLUDE,
    // becoming DEP_OPENBLAS_LIBRARY / DEP_OPENBLAS_INCLUDE. It builds in-tree so
    // DEP_OPENBLAS_LIBRARY is the directory containing libopenblas.a directly.
    let openblas_lib_dir = PathBuf::from(env::var("DEP_OPENBLAS_LIBRARY").expect(
        "DEP_OPENBLAS_LIBRARY not set – is openblas-src a dependency with the 'static' feature?",
    ));
    let openblas_static_lib = openblas_lib_dir.join("libopenblas.a");
    let openblas_include_dir = PathBuf::from(
        env::var("DEP_OPENBLAS_INCLUDE")
            .unwrap_or_else(|_| openblas_lib_dir.to_string_lossy().into_owned()),
    );
    println!(
        "cargo:warning=Using static OpenBLAS: {}",
        openblas_static_lib.display()
    );

    // Native dependency install prefixes, each built by its own -sys crate and
    // exported as DEP_CP2K_<NAME>_ROOT (links = "cp2k_<name>"). libxsmm is
    // architecture-restricted: its crate exports nothing on unsupported arches.
    let dep_root = |k: &str| {
        PathBuf::from(env::var(k).unwrap_or_else(|_| {
            panic!("{k} not set – the corresponding -sys crate must be a dependency")
        }))
    };
    let fftw3_install = dep_root("DEP_CP2K_FFTW3_ROOT");
    let dbcsr_install_dir = dep_root("DEP_CP2K_DBCSR_ROOT");
    let scalapack_install = dep_root("DEP_CP2K_SCALAPACK_ROOT");
    let libxc_install = dep_root("DEP_CP2K_LIBXC_ROOT");
    let dftd4_install = dep_root("DEP_CP2K_DFTD4_ROOT");
    let libint_install = dep_root("DEP_CP2K_LIBINT_ROOT");
    let gauxc_install = dep_root("DEP_CP2K_GAUXC_ROOT");
    let libvori_install = dep_root("DEP_CP2K_LIBVORI_ROOT");
    let elpa_install = dep_root("DEP_CP2K_ELPA_ROOT");
    let cosma_install = dep_root("DEP_CP2K_COSMA_ROOT");
    let libsmeagol_install = dep_root("DEP_CP2K_LIBSMEAGOL_ROOT");
    let trexio_install = dep_root("DEP_CP2K_TREXIO_ROOT");
    let tblite_install = dep_root("DEP_CP2K_TBLITE_ROOT");
    let greenx_install = dep_root("DEP_CP2K_GREENX_ROOT");
    let gmp_install = dep_root("DEP_CP2K_GMP_ROOT");
    let libvdwxc_install = dep_root("DEP_CP2K_LIBVDWXC_ROOT");
    let plumed_install = dep_root("DEP_CP2K_PLUMED_ROOT");
    let zlib_install = dep_root("DEP_CP2K_ZLIB_ROOT");
    // PEXSI stack (PEXSI + SuperLU_DIST + ParMETIS) — only with the `pexsi`
    // feature. ParMETIS 4.0.3 carries a research-only license that forbids
    // redistribution, so public worker builds must not link it.
    let pexsi_enabled = env::var("CARGO_FEATURE_PEXSI").is_ok();
    let pexsi_install = pexsi_enabled.then(|| dep_root("DEP_CP2K_PEXSI_ROOT"));
    let superlu_dist_install = pexsi_enabled.then(|| dep_root("DEP_CP2K_SUPERLU_DIST_ROOT"));
    let parmetis_install = pexsi_enabled.then(|| dep_root("DEP_CP2K_PARMETIS_ROOT"));
    let libxsmm_install = env::var("DEP_CP2K_LIBXSMM_ROOT").ok().map(PathBuf::from);

    // SIRIUS (plane-wave DFT) + its dependency stack, statically linked like every
    // other native dependency.
    let sirius_deps = SiriusDeps {
        sirius: dep_root("DEP_CP2K_SIRIUS_ROOT"),
        gsl: dep_root("DEP_CP2K_GSL_ROOT"),
        spglib: dep_root("DEP_CP2K_SPGLIB_ROOT"),
        pugixml: dep_root("DEP_CP2K_PUGIXML_ROOT"),
        spfft: dep_root("DEP_CP2K_SPFFT_ROOT"),
        spla: dep_root("DEP_CP2K_SPLA_ROOT"),
        costa: dep_root("DEP_CP2K_COSTA_ROOT"),
        hdf5: dep_root("DEP_CP2K_HDF5_ROOT"),
        fmt: dep_root("DEP_CP2K_FMT_ROOT"),
    };

    let cp2k_build_dir = cp2k_stable_dir.join("build");
    // CP2K's CMakeCache bakes in absolute paths discovered from its
    // dependencies — including version-bearing ones like ELPA's
    // `include/elpa_openmp-<version>/modules` and libxc's `Libxc_DIR`. When a
    // dependency is bumped (its `-sys` crate installs a new version into the
    // same stable prefix), those cached paths become stale and the CP2K
    // compile fails ("elpa_constants.mod ... not found"). Each versioned
    // dependency writes a `.version` marker next to its install; fingerprint
    // all of them and wipe CP2K's build dir for a clean reconfigure whenever
    // the set changes. Cheap when nothing moved (no CP2K rebuild).
    let deps_fingerprint = {
        let mut roots: Vec<(String, String)> = env::vars()
            .filter(|(k, _)| k.starts_with("DEP_CP2K_") && k.ends_with("_ROOT"))
            .map(|(k, v)| {
                let marker = PathBuf::from(&v)
                    .parent()
                    .map(|p| p.join(".version"))
                    .and_then(|m| std::fs::read_to_string(m).ok())
                    .unwrap_or_default();
                (k, format!("{v}={}", marker.trim()))
            })
            .collect();
        roots.sort();
        roots
            .into_iter()
            .map(|(_, v)| v)
            .collect::<Vec<_>>()
            .join("\n")
    };
    let fp_file = cp2k_stable_dir.join(".deps-fingerprint");
    let fp_stale = std::fs::read_to_string(&fp_file)
        .map(|prev| prev != deps_fingerprint)
        .unwrap_or(true);
    if fp_stale && cp2k_build_dir.exists() {
        println!(
            "cargo:warning=A CP2K dependency changed version – wiping the CP2K build dir for a clean reconfigure..."
        );
        std::fs::remove_dir_all(&cp2k_build_dir).expect("Failed to remove stale CP2K build dir");
    }
    std::fs::create_dir_all(&cp2k_build_dir).expect("Failed to create CP2K build directory");

    configure_cp2k_cmake(
        &cp2k_src_dir,
        &cp2k_build_dir,
        &dbcsr_install_dir,
        &openblas_static_lib,
        &openblas_include_dir,
        &fftw3_install,
        &scalapack_install,
        &libxc_install,
        libxsmm_install.as_deref(),
        &dftd4_install,
        &libint_install,
        &gauxc_install,
        &libvori_install,
        &elpa_install,
        &cosma_install,
        &libsmeagol_install,
        &sirius_deps,
        &trexio_install,
        &tblite_install,
        &greenx_install,
        &gmp_install,
        &libvdwxc_install,
        &plumed_install,
        &zlib_install,
        pexsi_install.as_deref(),
        superlu_dist_install.as_deref(),
        parmetis_install.as_deref(),
    );
    // Record what this build dir is *configured* for, right after configuring
    // and before the long compile. Writing it after a successful build instead
    // describes the last thing that built, which is a different fact and leaves
    // a trap: bump a dependency, watch the compile fail, put the old version
    // back — and the fingerprint still says "old", so nothing is wiped and CMake
    // keeps the cached <pkg>_DIR paths from the failed attempt. CP2K then builds
    // against a mix of both versions. That cost a full rebuild to find, with
    // CMAKE_PREFIX_PATH pointing at tblite 0.6 while s-dftd3_DIR still resolved
    // into the 0.7 tree.
    std::fs::write(&fp_file, &deps_fingerprint).ok();
    build_cp2k_cmake(&cp2k_build_dir);

    if cfg!(feature = "extended") {
        println!("cargo:warning=Building Fortran extensions for extended interface...");
        build_fortran_extensions(&cp2k_src_dir, &cp2k_build_dir, &out_dir);
    }

    let libcp2k_path = find_libcp2k(&cp2k_build_dir);
    let cp2k_lib_dir = libcp2k_path.parent().unwrap();

    // ── Export install paths for the parent crate's linker step ──────────────
    // links = "cp2k", so each `cargo:KEY=VALUE` becomes DEP_CP2K_<KEY> for cp2k-rs.
    let emit = |k: &str, v: &Path| println!("cargo:{k}={}", v.display());
    emit("cp2k_lib_dir", cp2k_lib_dir);

    // Which CP2K this worker actually contains. Without it a nightly build
    // against upstream master and a pinned release build are indistinguishable
    // once installed — `--worker-info` reports cp2k-rs's own version and commit,
    // which are identical for both — and a result cannot be attributed to the
    // CP2K it came from.
    let built_commit = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(&cp2k_src_dir)
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|| "unknown".to_string());
    let built_ref = cp2k_git_ref_override().unwrap_or_else(|| CP2K_GIT_BRANCH.to_string());
    println!("cargo:cp2k_source_ref={built_ref}");
    println!("cargo:cp2k_source_commit={built_commit}");
    println!("cargo:warning=CP2K source: {built_ref} @ {built_commit}");
    emit("dbcsr_lib_dir", &dbcsr_install_dir.join("lib"));
    emit("fftw3_lib_dir", &fftw3_install.join("lib"));
    emit("scalapack_lib_dir", &scalapack_install.join("lib"));
    emit("libxc_lib_dir", &libxc_install.join("lib"));
    emit("dftd4_lib_dir", &dftd4_install.join("lib"));
    emit("libint_lib_dir", &libint_install.join("lib"));
    emit("gauxc_lib_dir", &gauxc_install.join("lib"));
    // Skala variant only: re-export libtorch's lib dir so the parent crate can
    // add the (dynamic) libtorch link. Absent in the default build.
    if let Ok(libtorch_root) = std::env::var("DEP_CP2K_LIBTORCH_ROOT") {
        emit(
            "libtorch_lib_dir",
            &PathBuf::from(libtorch_root).join("lib"),
        );
    }
    emit("libvori_lib_dir", &libvori_install.join("lib"));
    emit("elpa_lib_dir", &elpa_install.join("lib"));
    emit("cosma_lib_dir", &cosma_install.join("lib"));
    emit("libsmeagol_lib_dir", &libsmeagol_install.join("lib"));
    emit("trexio_lib_dir", &trexio_install.join("lib"));
    emit("tblite_lib_dir", &tblite_install.join("lib"));
    emit("greenx_lib_dir", &greenx_install.join("lib"));
    emit("gmp_lib_dir", &gmp_install.join("lib"));
    emit("libvdwxc_lib_dir", &libvdwxc_install.join("lib"));
    emit("plumed_lib_dir", &plumed_install.join("lib"));
    emit("zlib_lib_dir", &zlib_install.join("lib"));
    if let (Some(pexsi), Some(superlu_dist), Some(parmetis)) =
        (&pexsi_install, &superlu_dist_install, &parmetis_install)
    {
        emit("pexsi_lib_dir", &pexsi.join("lib"));
        emit("superlu_dist_lib_dir", &superlu_dist.join("lib"));
        emit("parmetis_lib_dir", &parmetis.join("lib"));
    }
    if let Some(libxsmm) = &libxsmm_install {
        emit("libxsmm_lib_dir", &libxsmm.join("lib"));
    }

    // SIRIUS dependency lib dirs.
    emit("sirius_lib_dir", &sirius_deps.sirius.join("lib"));
    emit("gsl_lib_dir", &sirius_deps.gsl.join("lib"));
    emit("spglib_lib_dir", &sirius_deps.spglib.join("lib"));
    emit("pugixml_lib_dir", &sirius_deps.pugixml.join("lib"));
    emit("spfft_lib_dir", &sirius_deps.spfft.join("lib"));
    emit("spla_lib_dir", &sirius_deps.spla.join("lib"));
    emit("costa_lib_dir", &sirius_deps.costa.join("lib"));
    emit("hdf5_lib_dir", &sirius_deps.hdf5.join("lib"));
    emit("fmt_lib_dir", &sirius_deps.fmt.join("lib"));

    emit("openblas_lib", &openblas_static_lib);
    if let Some(mpi_lib_dir) = find_mpi_lib_dir(&mpi_base_dir) {
        emit("mpi_lib_dir", &mpi_lib_dir);
    }
    if cfg!(feature = "extended") {
        let extended_lib_dir = out_dir.join("extensions_lib");
        if extended_lib_dir.join("libcp2k_extended.a").exists() {
            emit("extended_lib_dir", &extended_lib_dir);
        }
    }
}

fn detect_mpi_installation() -> PathBuf {
    // Preferred: locate the `mpicc` wrapper itself (on PATH, e.g. after
    // `module load mpi/openmpi-x86_64`) and take its bin dir's parent as the
    // MPI prefix. This yields a prefix whose `bin/` and `lib{,64}/` are valid
    // (unlike parsing `--showme:compile`, whose include dir may be nested, e.g.
    // /usr/include/openmpi-x86_64, giving a wrong prefix).
    if let Ok(output) = Command::new("which").arg("mpicc").output()
        && output.status.success()
    {
        let mpicc = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
        if let Some(base) = mpicc.parent().and_then(Path::parent) {
            return base.to_path_buf();
        }
    }

    // Check common OpenMPI installation paths directly.
    let common_paths = [
        "/usr/lib64/openmpi",
        "/usr/lib/x86_64-linux-gnu/openmpi",
        "/usr/local",
        "/opt/openmpi",
    ];
    for path in &common_paths {
        let path_buf = PathBuf::from(path);
        if path_buf.join("bin").join("mpicc").exists()
            || path_buf.join("include").join("mpi.h").exists()
        {
            return path_buf;
        }
    }

    panic!(
        "Could not find MPI installation. Ensure OpenMPI is installed (checked PATH and common locations like /usr/lib64/openmpi)."
    );
}

fn find_mpi_lib_dir(mpi_base_dir: &Path) -> Option<PathBuf> {
    let lib_candidates = ["lib64", "lib"];

    for lib_subdir in &lib_candidates {
        let lib_dir = mpi_base_dir.join(lib_subdir);
        if lib_dir.exists() {
            return Some(lib_dir);
        }
    }
    None
}

/// MPI `pkgconfig` directory, derived from the detected MPI installation, with the
/// RHEL/OpenMPI layout as a fallback. Lets the DBCSR/ScaLAPACK/CP2K CMake builds
/// locate the MPI `.pc` files on non-RHEL systems (Debian, custom installs) too.
fn mpi_pkgconfig_dir() -> String {
    if let Some(lib) = find_mpi_lib_dir(&detect_mpi_installation()) {
        let pc = lib.join("pkgconfig");
        if pc.is_dir() {
            return pc.to_string_lossy().into_owned();
        }
    }
    "/usr/lib64/openmpi/lib/pkgconfig".to_string()
}

/// Install prefixes of SIRIUS and its dependency stack. Only constructed when
/// the `sirius` feature is enabled.
struct SiriusDeps {
    sirius: PathBuf,
    gsl: PathBuf,
    spglib: PathBuf,
    pugixml: PathBuf,
    spfft: PathBuf,
    spla: PathBuf,
    costa: PathBuf,
    hdf5: PathBuf,
    fmt: PathBuf,
}

fn configure_cp2k_cmake(
    cp2k_src_dir: &Path,
    cp2k_build_dir: &Path,
    dbcsr_install_dir: &Path,
    openblas_static_lib: &Path,
    openblas_include_dir: &Path,
    fftw3_install: &Path,
    scalapack_install: &Path,
    libxc_install: &Path,
    libxsmm_install: Option<&Path>,
    dftd4_install: &Path,
    libint_install: &Path,
    gauxc_install: &Path,
    libvori_install: &Path,
    elpa_install: &Path,
    cosma_install: &Path,
    libsmeagol_install: &Path,
    sirius: &SiriusDeps,
    trexio_install: &Path,
    tblite_install: &Path,
    greenx_install: &Path,
    gmp_install: &Path,
    libvdwxc_install: &Path,
    plumed_install: &Path,
    zlib_install: &Path,
    pexsi_install: Option<&Path>,
    superlu_dist_install: Option<&Path>,
    parmetis_install: Option<&Path>,
) {
    println!("cargo:warning=Configuring CP2K with CMake...");

    let num_jobs = env::var("NUM_JOBS").unwrap_or_else(|_| num_cpus::get().to_string());
    let mpi_bin = detect_mpi_installation().join("bin");

    // Build up PKG_CONFIG_PATH: prepend the OpenMPI pkgconfig dir so CMake's
    // FindSCALAPACK can locate scalapack.pc via pkg-config.
    // (libxsmm's pkgconfig dir is no longer added: CP2K 2026.2 only consumes
    // LIBXSMM through the new LIBXS backend, which we do not enable; libxsmm
    // itself is still built for DBCSR.)
    let openmpi_pkgconfig = mpi_pkgconfig_dir();
    let mut pkg_config_dirs = vec![openmpi_pkgconfig.clone()];
    let _ = libxsmm_install; // kept for the DEP_CP2K_LIBXSMM_LIB_DIR export only
    // CP2K's FindElpa resolves ELPA exclusively via pkg-config (elpa_openmp.pc).
    pkg_config_dirs.push(
        elpa_install
            .join("lib")
            .join("pkgconfig")
            .display()
            .to_string(),
    );
    // SIRIUS's FindLibVDWXC (re-run transitively by CP2K's find_package(sirius))
    // discovers libvdwxc via pkg-config.
    pkg_config_dirs.push(
        libvdwxc_install
            .join("lib")
            .join("pkgconfig")
            .display()
            .to_string(),
    );
    // CP2K's FindPlumed uses pkg-config (plumed.pc) first.
    pkg_config_dirs.push(
        plumed_install
            .join("lib")
            .join("pkgconfig")
            .display()
            .to_string(),
    );
    let pkg_config_path = match env::var("PKG_CONFIG_PATH") {
        Ok(existing) => format!("{}:{existing}", pkg_config_dirs.join(":")),
        Err(_) => pkg_config_dirs.join(":"),
    };

    // CMAKE_PREFIX_PATH: FFTW3, DBCSR, ScaLAPACK, Libxc, DFT-D4 install dirs.
    // OpenBLAS is passed via explicit library/include variables. When SIRIUS is
    // enabled, its config (find_package(sirius)) transitively resolves GSL,
    // HDF5, pugixml, SpFFT, SpLA and COSTA, so their prefixes / CMake config
    // dirs are appended here.
    let mut prefix_entries = vec![
        fftw3_install.display().to_string(),
        dbcsr_install_dir.display().to_string(),
        scalapack_install.display().to_string(),
        libxc_install.display().to_string(),
        dftd4_install.display().to_string(),
        // Libint2: find_package(Libint2 CONFIG) since CP2K 2026.2.
        libint_install.display().to_string(),
        // GauXC: find_package(gauxc CONFIG); ExchCXX is installed into the
        // same prefix by cp2k-gauxc-sys.
        gauxc_install.display().to_string(),
    ];
    // Skala variant: GauXC's installed config does find_dependency(Torch) when
    // built with ONEDFT, so CP2K's find_package(gauxc) transitively needs the
    // libtorch prefix on CMAKE_PREFIX_PATH (TorchConfig.cmake lives under
    // <libtorch>/share/cmake/Torch).
    if let Ok(libtorch_root) = std::env::var("DEP_CP2K_LIBTORCH_ROOT") {
        prefix_entries.push(libtorch_root);
    }
    // tblite installs CMake config packages for tblite + the two sub-deps it
    // FetchContent-builds (toml-f, s-dftd3); mctc-lib/dftd4/multicharge come
    // from the dftd4-sys prefix above.
    prefix_entries.push(tblite_install.display().to_string());
    // GreenX installs greenXConfig.cmake under lib/cmake/greenX.
    prefix_entries.push(greenx_install.display().to_string());
    // PLUMED installs plumed.pc under lib/pkgconfig (also found via PKG_CONFIG_PATH).
    prefix_entries.push(plumed_install.display().to_string());
    // PEXSI (only with the `pexsi` feature): PEXSIConfig.cmake under
    // lib/cmake/PEXSI; SuperLU_DIST + ParMETIS also need their prefixes for
    // find_package resolution.
    if let (Some(pexsi), Some(superlu_dist), Some(parmetis)) =
        (pexsi_install, superlu_dist_install, parmetis_install)
    {
        prefix_entries.push(pexsi.display().to_string());
        prefix_entries.push(superlu_dist.display().to_string());
        prefix_entries.push(parmetis.display().to_string());
    }
    prefix_entries.push(sirius.sirius.join("lib/cmake/sirius").display().to_string());
    prefix_entries.push(
        sirius
            .sirius
            .join("lib/cmake/sirius_cxx")
            .display()
            .to_string(),
    );
    prefix_entries.push(sirius.gsl.display().to_string());
    prefix_entries.push(sirius.hdf5.display().to_string());
    prefix_entries.push(sirius.pugixml.display().to_string());
    prefix_entries.push(sirius.fmt.display().to_string());
    prefix_entries.push(sirius.spfft.join("lib/cmake/SpFFT").display().to_string());
    prefix_entries.push(sirius.spla.join("lib/cmake/SPLA").display().to_string());
    prefix_entries.push(sirius.costa.join("lib/cmake/costa").display().to_string());
    prefix_entries.push(cosma_install.join("lib/cmake/cosma").display().to_string());
    // ROCm CMake packages (hip, hiprtc, rocblas, etc.) — needed when DBCSR is
    // built with HIP and exports those as interface dependencies.
    #[cfg(feature = "hip")]
    {
        let rocm_path = env::var("ROCM_PATH").unwrap_or_else(|_| "/opt/rocm".into());
        prefix_entries.push(rocm_path.clone());
        prefix_entries.push(format!("{rocm_path}/lib/cmake"));
    }
    // CUDA toolkit — find_package(CUDAToolkit) in CP2K's CMake needs this
    // when CUDA is not in the default /usr/local/cuda location.
    #[cfg(feature = "cuda")]
    {
        let cuda_path = env::var("CUDA_PATH").unwrap_or_else(|_| "/usr/local/cuda".into());
        prefix_entries.push(cuda_path);
    }
    let cmake_prefix_path = prefix_entries.join(";");

    let mut args: Vec<String> = vec![
        "-S".into(),
        cp2k_src_dir.to_string_lossy().into_owned(),
        "-B".into(),
        cp2k_build_dir.to_string_lossy().into_owned(),
        "-DCMAKE_BUILD_TYPE=Release".into(),
        "-DBUILD_SHARED_LIBS=OFF".into(),
        "-DCP2K_USE_MPI=ON".into(),
        "-DCP2K_USE_FFTW3=ON".into(),
        "-DCP2K_USE_BLAS=ON".into(),
        "-DCP2K_USE_LAPACK=ON".into(),
        "-DCP2K_USE_SCALAPACK=ON".into(),
        // Statically-built optional dependencies (no new dynamic deps).
        "-DCP2K_USE_LIBXC=ON".into(),
        "-DCP2K_USE_DFTD4=ON".into(),
        // spglib is intentionally disabled for CP2K itself: with k-points its
        // symmetry path (kpsym.F) aborts in CP2K's library/worker mode. (SIRIUS
        // uses its own copy of spglib internally; that is unaffected.)
        "-DCP2K_USE_SPGLIB=OFF".into(),
        // Libint2: Hartree-Fock exchange / hybrid functionals. CP2K 2026.2
        // discovers it via find_package(Libint2 CONFIG) — resolved through the
        // libint prefix on CMAKE_PREFIX_PATH below.
        "-DCP2K_USE_LIBINT2=ON".into(),
        // GauXC: molecular-quadrature XC integrator (conventional functionals
        // via ExchCXX/Libxc). Built without ONEDFT: Skala ML models require
        // libtorch, which cannot be linked statically without unreasonable
        // cost — and dynamic libtorch would add new worker dependencies.
        "-DCP2K_USE_GAUXC=ON".into(),
        // libvori: Voronoi integration + BQB compression.
        "-DCP2K_USE_VORI=ON".into(),
        format!("-DCP2K_LIBVORI_ROOT={}", libvori_install.display()),
        // ELPA: fast distributed eigensolvers (PREFERRED_DIAG_LIBRARY ELPA).
        "-DCP2K_USE_ELPA=ON".into(),
        "-DCP2K_ENABLE_ELPA_OPENMP_SUPPORT=ON".into(),
        // COSMA: communication-optimal pdgemm replacement.
        "-DCP2K_USE_COSMA=ON".into(),
        // libsmeagol: SMEAGOL NEGF electron transport.
        "-DCP2K_USE_LIBSMEAGOL=ON".into(),
        format!("-DCP2K_LIBSMEAGOL_ROOT={}", libsmeagol_install.display()),
        // TREXIO: wavefunction export to QMC codes (statically linked).
        "-DCP2K_USE_TREXIO=ON".into(),
        format!("-DTREXIO_ROOT={}", trexio_install.display()),
        // tblite: xTB semiempirical tight-binding (GFN1/GFN2), statically linked.
        "-DCP2K_USE_TBLITE=ON".into(),
        // GreenX: low-scaling RPA + GW via minimax grids (statically linked).
        "-DCP2K_USE_GREENX=ON".into(),
        // libvdwxc: nonlocal vdW-DF functionals via SIRIUS plane-wave.
        "-DCP2K_USE_LIBVDWXC=ON".into(),
        // PLUMED: enhanced-sampling MD (metadynamics, umbrella sampling).
        "-DCP2K_USE_PLUMED=ON".into(),
        // CP2K's CMake unconditionally does find_library(GMP_LIBRARY NAMES gmp
        // REQUIRED) for GreenX. Point it at our static libgmp.a so no system
        // libgmp.so is picked up.
        format!(
            "-DGMP_LIBRARY={}",
            gmp_install.join("lib/libgmp.a").display()
        ),
        // dftd4's and gauxc's installed CMake configs transitively do
        // find_package(BLAS); there is no system BLAS here, so hand them our
        // static OpenBLAS to short-circuit FindBLAS/FindLAPACK (CP2K itself
        // uses CP2K_BLAS_* below). The runtime libs must be included: gauxc's
        // bundled linalg-cmake-modules FindBLAS misdetects the Fortran
        // mangling (concluding an underscore-less dgemm) when its first link
        // test fails for unrelated missing-symbol reasons.
        format!(
            "-DBLAS_LIBRARIES={};gfortran;gomp;pthread;m",
            openblas_static_lib.display()
        ),
        format!(
            "-DLAPACK_LIBRARIES={};gfortran;gomp;pthread;m",
            openblas_static_lib.display()
        ),
        "-DCMAKE_POSITION_INDEPENDENT_CODE=ON".into(),
        // Use statically-built OpenBLAS for BLAS + LAPACK.
        // CUSTOM vendor lets us bypass auto-detection entirely.
        "-DCP2K_BLAS_VENDOR=CUSTOM".into(),
        format!(
            "-DCP2K_BLAS_LINK_LIBRARIES={}",
            openblas_static_lib.display()
        ),
        format!(
            "-DCP2K_LAPACK_LINK_LIBRARIES={}",
            openblas_static_lib.display()
        ),
        format!(
            "-DCP2K_BLAS_INCLUDE_DIRS={}",
            openblas_include_dir.display()
        ),
        // Use statically-built FFTW3 with OpenMP support
        format!("-DCP2K_FFTW3_ROOT={}", fftw3_install.display()),
        "-DCP2K_ENABLE_FFTW3_OPENMP_SUPPORT=ON".into(),
        format!(
            "-DCMAKE_PREFIX_PATH={cmake_prefix_path}{}",
            rocm_cmake_prefix_suffix()
        ),
        format!(
            "-DCMAKE_Fortran_COMPILER={}",
            mpi_bin.join("mpifort").display()
        ),
        format!("-DCMAKE_C_COMPILER={}", mpi_bin.join("mpicc").display()),
        format!("-DCMAKE_CXX_COMPILER={}", mpi_bin.join("mpicxx").display()),
        format!("-DCMAKE_C_FLAGS={}", march_flag(&cp2k_target_arch())),
        format!("-DCMAKE_CXX_FLAGS={}", march_flag(&cp2k_target_arch())),
        format!("-DCMAKE_Fortran_FLAGS={}", march_flag(&cp2k_target_arch())),
        format!("-DCMAKE_BUILD_PARALLEL_LEVEL={num_jobs}"),
    ];

    // PEXSI: reduced-scaling DFT via pole expansion + selected inversion
    // (only with the `pexsi` feature — ParMETIS license, see main()).
    if pexsi_install.is_some() {
        args.push("-DCP2K_USE_PEXSI=ON".into());
    }

    // GPU acceleration (CUDA or HIP). When enabled, CP2K compiles GPU kernels
    // (.cu / .hip files) and links dynamically against the GPU runtime libs
    // (libcudart.so / libamdhip64.so etc.). The build requires nvcc or hipcc.
    // At runtime, CP2K uses the GPU when available and falls back to CPU.
    #[cfg(feature = "cuda")]
    {
        println!("cargo:warning=Enabling CUDA GPU acceleration...");
        let cuda_arch = env::var("CP2K_CUDA_ARCH").unwrap_or_else(|_| "80".into());
        args.push("-DCP2K_USE_ACCEL=CUDA".into());
        args.push(format!("-DCMAKE_CUDA_ARCHITECTURES={cuda_arch}"));
        // Enable GPU backends for grid, DBM, and PW.
        args.push("-DCP2K_ENABLE_GRID_GPU=ON".into());
        args.push("-DCP2K_ENABLE_DBM_GPU=ON".into());
        args.push("-DCP2K_ENABLE_PW_GPU=ON".into());
    }
    #[cfg(feature = "hip")]
    {
        println!("cargo:warning=Enabling HIP/ROCm GPU acceleration...");
        let hip_arch = env::var("CP2K_HIP_ARCH").unwrap_or_else(|_| "gfx90a".into());
        args.push("-DCP2K_USE_ACCEL=HIP".into());
        args.push(format!("-DCMAKE_HIP_ARCHITECTURES={hip_arch}"));
        args.push("-DCP2K_ENABLE_GRID_GPU=ON".into());
        args.push("-DCP2K_ENABLE_DBM_GPU=ON".into());
        args.push("-DCP2K_ENABLE_PW_GPU=ON".into());
    }
    #[cfg(not(any(feature = "cuda", feature = "hip")))]
    {
        args.push("-DCP2K_USE_ACCEL=NONE".into());
    }

    // SIRIUS interface. Its config re-runs find_dependency() for the whole
    // stack, so hand CMake the static-HDF5 / GSL / OpenBLAS hints it needs.
    println!("cargo:warning=Enabling SIRIUS support...");
    let openblas_lib_dir = openblas_static_lib.parent().unwrap();
    args.push("-DCP2K_USE_SIRIUS=ON".into());
    args.push(format!("-DHDF5_ROOT={}", sirius.hdf5.display()));
    args.push("-DHDF5_USE_STATIC_LIBRARIES=ON".into());
    args.push("-DHDF5_PREFER_PARALLEL=OFF".into());
    args.push(format!("-DGSL_ROOT_DIR={}", sirius.gsl.display()));
    // find_dependency(LAPACK) from the SIRIUS config: use static OpenBLAS.
    args.push("-DBLA_VENDOR=OpenBLAS".into());
    args.push("-DBLA_STATIC=ON".into());
    args.push(format!(
        "-DCMAKE_LIBRARY_PATH={}",
        openblas_lib_dir.display()
    ));

    let mut cmd = Command::new("cmake");
    cmd.args(&args)
        .env("PKG_CONFIG_PATH", &pkg_config_path)
        // Hints for SIRIUS's bundled Find modules (spglib -> `symspg`, Libxc -> `xc`,
        // ScaLAPACK -> `scalapack`; the latter is used by the SIRIUS and COSTA
        // configs' transitive find_dependency(SCALAPACK)).
        .env("SPG_DIR", sirius.spglib.display().to_string())
        .env("LIBXCROOT", libxc_install.display().to_string())
        .env("GSL_ROOT_DIR", sirius.gsl.display().to_string())
        .env("SCALAPACKROOT", scalapack_install.display().to_string())
        // CP2K's cp2k_set_default_paths(LIBVORI ...) also probe env vars.
        .env("LIBVORI_ROOT", libvori_install.display().to_string())
        .env("LIBSMEAGOL_ROOT", libsmeagol_install.display().to_string())
        // CP2K's FindTrexIO falls back to cp2k_find_libraries/cp2k_include_dirs
        // using the TREXIO_ROOT env var (no pkg-config .pc from the CMake build).
        .env("TREXIO_ROOT", trexio_install.display().to_string())
        // COSMA's installed config re-runs find_dependency(OPENBLAS); its
        // FindOPENBLAS needs both the library dir and the cblas.h dir as hints.
        .env(
            "OPENBLAS_ROOT",
            openblas_static_lib.parent().unwrap().display().to_string(),
        )
        .env("OPENBLAS_DIR", openblas_include_dir.display().to_string());
    let output = cmd
        .output()
        .expect("Failed to run cmake configure. Make sure cmake is installed.");

    if !output.status.success() {
        eprintln!("CMake configure failed!");
        eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        panic!("CP2K CMake configuration failed");
    }

    println!("cargo:warning=CP2K CMake configuration completed");
}

fn build_cp2k_cmake(cp2k_build_dir: &Path) {
    println!("cargo:warning=Building CP2K with CMake - this may take 30+ minutes...");

    let num_jobs = env::var("NUM_JOBS").unwrap_or_else(|_| num_cpus::get().to_string());

    // Extend PATH and PYTHONPATH so fypp (used to preprocess Fortran files) is found.
    // If HOME is not set, skip the ~/.local candidate paths (they cannot exist without a
    // home directory) and warn, rather than assuming a hard-coded path like "/root".
    let home = env::var("HOME").ok();
    let extended_path = {
        let base = env::var("PATH").unwrap_or_else(|_| "/usr/local/bin:/usr/bin:/bin".to_string());
        match home.as_ref() {
            Some(h) => format!("{h}/.local/bin:{base}"),
            None => {
                println!(
                    "cargo:warning=HOME not set; cannot extend PATH with ~/.local/bin for fypp"
                );
                base
            }
        }
    };
    let extended_pythonpath = {
        let base = env::var("PYTHONPATH").unwrap_or_default();
        let extra: String = match home.as_ref() {
            Some(h) => {
                let candidates = [
                    format!("{h}/.local/lib/python3.12/site-packages"),
                    format!("{h}/.local/lib/python3.11/site-packages"),
                    format!("{h}/.local/lib/python3.10/site-packages"),
                    format!("{h}/.local/lib/python3.9/site-packages"),
                ];
                candidates.join(":")
            }
            None => {
                println!(
                    "cargo:warning=HOME not set; cannot extend PYTHONPATH with ~/.local site-packages for fypp"
                );
                String::new()
            }
        };
        if extra.is_empty() {
            base
        } else if base.is_empty() {
            extra
        } else {
            format!("{extra}:{base}")
        }
    };

    let output = Command::new("cmake")
        .args([
            "--build",
            cp2k_build_dir.to_str().unwrap(),
            "--target",
            "cp2k",
            "-j",
            &num_jobs,
        ])
        .env("PATH", &extended_path)
        .env("PYTHONPATH", &extended_pythonpath)
        .output()
        .expect("Failed to execute CP2K CMake build");

    if !output.status.success() {
        eprintln!("CP2K build failed!");
        eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        panic!("CP2K compilation failed");
    }

    println!("cargo:warning=CP2K build completed successfully");
}

fn find_libcp2k(cp2k_build_dir: &Path) -> PathBuf {
    // CMake puts static libraries in {build_dir}/lib/
    let lib_path = cp2k_build_dir.join("lib").join("libcp2k.a");

    if lib_path.exists() {
        return lib_path;
    }

    panic!("Could not find libcp2k.a at {lib_path:?} after building");
}

fn clone_cp2k_repository(out_dir: &Path) -> PathBuf {
    let cp2k_src_dir = out_dir.join("cp2k");

    // A cached checkout (e.g. from a CI cache) may still be at a previous
    // pinned commit. The build below is incremental and would silently keep
    // building the old version, so wipe checkout + CMake build dir on mismatch.
    if cp2k_src_dir.exists() {
        let current_sha = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&cp2k_src_dir)
            .output()
            .ok()
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
        // With an override the checkout tracks a moving branch, so there is no
        // pinned SHA to compare against; `git fetch` below brings it forward
        // instead of wiping and re-cloning a full tree every night.
        let matches = if cp2k_git_ref_override().is_some() {
            true
        } else {
            let pinned = CP2K_GIT_COMMIT.to_string();
            current_sha
                .as_deref()
                .map(|s| s == pinned || s.starts_with(&pinned) || pinned.starts_with(s))
                .unwrap_or(false)
        };
        if !matches {
            println!(
                "cargo:warning=Existing CP2K checkout is at {:?}, expected {CP2K_GIT_COMMIT} – wiping and re-cloning...",
                current_sha.as_deref().unwrap_or("<unknown>")
            );
            std::fs::remove_dir_all(&cp2k_src_dir).expect("Failed to remove stale CP2K checkout");
            let stale_build_dir = out_dir.join("build");
            if stale_build_dir.exists() {
                std::fs::remove_dir_all(&stale_build_dir)
                    .expect("Failed to remove stale CP2K build dir");
            }
        }
    }

    let ref_override = cp2k_git_ref_override();
    let clone_ref = ref_override
        .clone()
        .unwrap_or_else(|| CP2K_GIT_BRANCH.to_string());

    if !cp2k_src_dir.exists() {
        println!("cargo:warning=Cloning CP2K repository at {clone_ref:?}...");

        let output = Command::new("git")
            .args([
                "clone",
                "--depth",
                "1",
                "--branch",
                &clone_ref,    // pinned release branch, or CP2K_GIT_REF
                "--recursive", // Clone submodules too
                "https://github.com/cp2k/cp2k.git",
                cp2k_src_dir.to_str().unwrap(),
            ])
            .output()
            .expect("Failed to clone CP2K repository. Make sure git is installed.");

        if !output.status.success() {
            panic!(
                "Failed to clone CP2K repository: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        // Verify the cloned HEAD matches the pinned commit. If the branch has
        // advanced upstream, abort rather than silently build a different
        // revision. To update: re-pin `CP2K_GIT_COMMIT` after testing.
        let cloned_sha = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&cp2k_src_dir)
            .output()
            .expect("Failed to read cloned CP2K HEAD");
        if !cloned_sha.status.success() {
            panic!(
                "Failed to read cloned CP2K HEAD: {}",
                String::from_utf8_lossy(&cloned_sha.stderr)
            );
        }
        let cloned = String::from_utf8_lossy(&cloned_sha.stdout)
            .trim()
            .to_string();
        if ref_override.is_none() && cloned != CP2K_GIT_COMMIT {
            panic!(
                "CP2K branch {CP2K_GIT_BRANCH:?} HEAD is {cloned}, but build is pinned to \
                 {CP2K_GIT_COMMIT}. The branch has advanced upstream — re-pin \
                 CP2K_GIT_COMMIT in crates/cp2k-sys/build.rs after verifying the new commit."
            );
        }

        println!("cargo:warning=CP2K repository cloned successfully at {cloned}");
    } else {
        println!("cargo:warning=CP2K repository already exists, updating submodules...");

        // An override tracks a moving branch, so an existing checkout has to be
        // brought forward — otherwise the staleness check above (which cannot
        // compare against a pin here) would keep this tree on whatever commit it
        // was first cloned at, and a nightly build would silently rebuild the
        // same old tip for ever. The pinned build never gets here with anything
        // but the pinned commit, so it is left alone.
        if let Some(git_ref) = &ref_override {
            let fetched = Command::new("git")
                .args(["fetch", "--depth", "1", "origin", git_ref])
                .current_dir(&cp2k_src_dir)
                .output()
                .expect("Failed to fetch the CP2K override ref");
            if !fetched.status.success() {
                panic!(
                    "Failed to fetch CP2K ref {git_ref:?}: {}",
                    String::from_utf8_lossy(&fetched.stderr)
                );
            }
            let reset = Command::new("git")
                .args(["reset", "--hard", "FETCH_HEAD"])
                .current_dir(&cp2k_src_dir)
                .output()
                .expect("Failed to reset the CP2K checkout to the fetched ref");
            if !reset.status.success() {
                panic!(
                    "Failed to reset CP2K to {git_ref:?}: {}",
                    String::from_utf8_lossy(&reset.stderr)
                );
            }
        }

        // Update submodules if the repository already exists
        let output = Command::new("git")
            .args(["submodule", "update", "--init", "--recursive"])
            .current_dir(&cp2k_src_dir)
            .output()
            .expect("Failed to update submodules");

        if !output.status.success() {
            panic!(
                "Failed to update submodules: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }
    }

    cp2k_src_dir
}

fn build_fortran_extensions(cp2k_src_dir: &Path, cp2k_build_dir: &Path, out_dir: &Path) {
    let extensions_dir =
        PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()).join("extensions/fortran");
    let obj_dir = out_dir.join("extensions_obj");
    let lib_dir = out_dir.join("extensions_lib");

    std::fs::create_dir_all(&obj_dir).expect("Failed to create obj dir");
    std::fs::create_dir_all(&lib_dir).expect("Failed to create lib dir");

    println!("cargo:warning=Compiling Fortran extensions...");

    // Get the CP2K source directory for includes
    let cp2k_src = cp2k_src_dir.join("src");

    // In CMake builds, .mod files are placed in {build_dir}/src/mod_files/
    let mod_files_dir = cp2k_build_dir.join("src").join("mod_files");

    if !mod_files_dir.exists() {
        panic!(
            "CP2K mod files directory not found: {}. Make sure CP2K is built before compiling extensions.",
            mod_files_dir.display()
        );
    }

    // Compile each Fortran source file
    let fortran_files = vec!["libcp2k_extended.F90", "libcp2k_mpi.F90"];

    let mut object_files = Vec::new();

    for fortran_file in &fortran_files {
        let src_path = extensions_dir.join(fortran_file);
        if !src_path.exists() {
            println!("cargo:warning=Skipping {} - file not found", fortran_file);
            continue;
        }

        let obj_name = fortran_file.replace(".F90", ".o").replace(".f90", ".o");
        let obj_path = obj_dir.join(&obj_name);

        println!("cargo:warning=Compiling {}...", fortran_file);

        let output = Command::new("mpifort")
            .args([
                "-c",
                "-fPIC",
                "-O2",
                "-g",
                "-ffree-form",
                "-ffree-line-length-none",
                "-fallow-argument-mismatch",
                "-D__parallel", // Enable MPI code paths in CP2K Fortran extensions
                &format!("-I{}", cp2k_src.display()),
                &format!("-I{}/base", cp2k_src.display()),
                &format!("-I{}", mod_files_dir.display()), // Add path to .mod files
                "-o",
                obj_path.to_str().unwrap(),
                src_path.to_str().unwrap(),
            ])
            .output()
            .unwrap_or_else(|_| panic!("Failed to compile {}", fortran_file));

        if !output.status.success() {
            eprintln!("Failed to compile {}", fortran_file);
            eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
            eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
            panic!("Fortran compilation failed for {}", fortran_file);
        }

        object_files.push(obj_path);
    }

    if object_files.is_empty() {
        println!("cargo:warning=No Fortran extension files compiled");
        return;
    }

    // Create a static library from the object files
    let lib_path = lib_dir.join("libcp2k_extended.a");

    println!("cargo:warning=Creating libcp2k_extended.a...");

    let output = Command::new("ar")
        .arg("rcs")
        .arg(&lib_path)
        .args(&object_files)
        .output()
        .expect("Failed to create archive");

    if !output.status.success() {
        eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
        panic!("Failed to create libcp2k_extended.a");
    }

    println!(
        "cargo:warning=Fortran extensions built successfully at {}",
        lib_path.display()
    );
}