bob 0.9.0

A pkgsrc package builder
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
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
/*
 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

//! Configuration file parsing (Lua format).
//!
//! Bob uses Lua configuration files for maximum flexibility. The configuration
//! defines paths to pkgsrc, packages to build, sandbox setup, and build scripts.
//!
//! # Configuration File Structure
//!
//! A configuration file has six main sections:
//!
//! - [`options`](#options-section) - General build options (optional)
//! - [`environment`](#environment-section) - Environment variable configuration (optional)
//! - [`pkgsrc`](#pkgsrc-section) - pkgsrc paths and package list (required)
//! - [`scripts`](#scripts-section) - Build script paths (required)
//! - [`sandboxes`](#sandboxes-section) - Sandbox configuration (optional)
//! - [`dynamic`](#dynamic-section) - Dynamic resource allocation (optional)
//!
//! # Options Section
//!
//! The `options` section is optional. All fields have defaults.
//!
//! | Field | Type | Default | Description |
//! |-------|------|---------|-------------|
//! | `build_threads` | integer | 1 | Number of parallel build sandboxes. Each sandbox builds one package at a time. |
//! | `dbdir` | string | "./db" | Directory for bob state files (database, tracing log). Relative to config file directory. |
//! | `scan_threads` | integer | 1 | Number of parallel scan processes for dependency discovery. |
//! | `strict_scan` | boolean | false | If true, abort on scan errors. If false, continue and report failures separately. |
//! | `log_level` | string | "info" | Log level: "trace", "debug", "info", "warn", or "error". Can be overridden by `RUST_LOG` env var. |
//!
//! # Environment Section
//!
//! The `environment` section is optional. It controls the environment variables
//! available to processes executed inside sandboxes.
//!
//! If this section is omitted, the parent environment is inherited unchanged.
//! If present, `clear` defaults to true and the environment is cleared before
//! applying the configured variables.
//!
//! | Field | Type | Default | Description |
//! |-------|------|---------|-------------|
//! | `clear` | boolean | true | If true, clear the environment. If false, inherit the full parent environment. |
//! | `inherit` | table | `{}` | Variable names to copy from the parent environment (only used when `clear = true`). |
//! | `set` | table | `{}` | Variables to set explicitly as key-value pairs. |
//!
//! To configure a minimal, controlled environment:
//!
//! ```lua
//! environment = {
//!     inherit = { "TERM", "HOME" },
//!     set = {
//!         PATH = "/sbin:/bin:/usr/sbin:/usr/bin",
//!     },
//! }
//! ```
//!
//! ## Precedence
//!
//! Variables are applied in this order (later values override earlier):
//!
//! 1. `inherit` - copied from parent process (only if `clear = true`)
//! 2. `set` - explicitly configured values
//! 3. `pkgsrc.cachevars` - values fetched from pkgsrc
//! 4. `pkgsrc.env` - per-package overrides
//! 5. `bob_*` - internal variables (always set, cannot be overridden)
//!
//! # Pkgsrc Section
//!
//! The `pkgsrc` section is required and defines paths to pkgsrc components.
//!
//! ## Required Fields
//!
//! | Field | Type | Description |
//! |-------|------|-------------|
//! | `basedir` | string | Absolute path to the pkgsrc source tree (e.g., `/data/pkgsrc`). |
//! | `make` | string | Absolute path to the bmake binary (e.g., `/usr/pkg/bin/bmake`). |
//!
//! ## Optional Fields
//!
//! | Field | Type | Default | Description |
//! |-------|------|---------|-------------|
//! | `bootstrap` | string | none | Path to a bootstrap tarball. Required on non-NetBSD systems. Unpacked into each sandbox before builds. |
//! | `build_user` | string | none | Unprivileged user to run builds as. If set, builds run as this user instead of root. |
//! | `logdir` | string | `dbdir/logs` | Directory for per-package build logs. Failed builds leave logs here; successful builds clean up. |
//! | `cachevars` | table | `{}` | List of pkgsrc variable names to fetch once and cache. These are set in the environment for scans and builds (e.g., `{"NATIVE_OPSYS", "NATIVE_OS_VERSION"}`). |
//! | `env` | function or table | `{}` | Environment variables for builds. Can be a table of key-value pairs, or a function receiving package metadata and returning a table. See [Environment Function](#environment-function). |
//! | `pkgpaths` | table | `{}` | List of package paths to build (e.g., `{"mail/mutt", "www/curl"}`). Dependencies are discovered automatically. |
//! | `save_wrkdir_patterns` | table | `{}` | Glob patterns for files to preserve from WRKDIR on build failure (e.g., `{"**/config.log"}`). |
//! | `tar` | string | `tar` | Path to a tar binary capable of extracting the bootstrap kit. Defaults to `tar` in PATH. |
//!
//! ## Environment Function
//!
//! The `env` field can be a function that returns environment variables for each
//! package build. The function receives a `pkg` table with the following fields:
//!
//! | Field | Type | Description |
//! |-------|------|-------------|
//! | `pkgname` | string | Package name with version (e.g., `mutt-2.2.12`). |
//! | `pkgpath` | string | Package path in pkgsrc (e.g., `mail/mutt`). |
//! | `all_depends` | string | Space-separated list of all transitive dependency paths. |
//! | `depends` | string | Space-separated list of direct dependency package names. |
//! | `scan_depends` | string | Space-separated list of scan-time dependency paths. |
//! | `categories` | string | Package categories from `CATEGORIES`. |
//! | `maintainer` | string | Package maintainer email from `MAINTAINER`. |
//! | `bootstrap_pkg` | string | Value of `BOOTSTRAP_PKG` if set. |
//! | `usergroup_phase` | string | Value of `USERGROUP_PHASE` if set. |
//! | `use_destdir` | string | Value of `USE_DESTDIR`. |
//! | `multi_version` | string | Value of `MULTI_VERSION` if set. |
//! | `pbulk_weight` | string | Value of `PBULK_WEIGHT` if set. |
//! | `pkg_skip_reason` | string | Value of `PKG_SKIP_REASON` if set. |
//! | `pkg_fail_reason` | string | Value of `PKG_FAIL_REASON` if set. |
//! | `no_bin_on_ftp` | string | Value of `NO_BIN_ON_FTP` if set. |
//! | `restricted` | string | Value of `RESTRICTED` if set. |
//!
//! # Scripts Section
//!
//! The `scripts` section defines paths to build scripts. Relative paths are
//! resolved from the configuration file's directory.
//!
//! | Script | Required | Description |
//! |--------|----------|-------------|
//! | `pre-build` | no | Executed before each package build. Used for per-build sandbox setup (e.g., unpacking bootstrap kit). Receives environment variables listed in [Script Environment](#script-environment). |
//! | `post-build` | no | Executed after each package build completes (success or failure). |
//!
//! ## Script Environment
//!
//! Build scripts receive these environment variables:
//!
//! | Variable | Description |
//! |----------|-------------|
//! | `bob_logdir` | Path to the build logs directory. |
//! | `bob_make` | Path to the bmake binary. |
//! | `bob_packages` | Path to the packages directory. |
//! | `bob_pkg_dbdir` | PKG_DBDIR from pkgsrc. |
//! | `bob_pkg_refcount_dbdir` | PKG_REFCOUNT_DBDIR from pkgsrc. |
//! | `bob_pkgtools` | Path to the pkg tools directory. |
//! | `bob_pkgsrc` | Path to the pkgsrc source tree. |
//! | `bob_prefix` | Installation prefix. |
//! | `bob_tar` | Path to the tar binary. |
//! | `bob_build_user` | Unprivileged build user, if configured. |
//! | `bob_build_user_home` | Home directory of the build user, if configured. |
//! | `bob_bootstrap` | Path to the bootstrap tarball, if configured. |
//!
//! # Sandboxes Section
//!
//! The `sandboxes` section is optional. When present, builds run in isolated
//! chroot environments.
//!
//! | Field | Type | Required | Description |
//! |-------|------|----------|-------------|
//! | `basedir` | string | yes | Base directory for sandbox roots. Sandboxes are created as numbered subdirectories (`basedir/0`, `basedir/1`, etc.). |
//! | `actions` | table | yes | List of actions to perform during sandbox setup. See the [`action`](crate::action) module for details. |

use crate::action::Action;
use crate::sandbox::Sandbox;
use crate::scan::ResolvedPackage;
use anyhow::{Context, Result, anyhow, bail};
use mlua::{Lua, RegistryKey, Result as LuaResult, Table, Value};
use pkgsrc::PkgPath;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

/// Environment variables retrieved from pkgsrc.
///
/// These values are queried from pkgsrc's mk.conf via bmake and represent
/// the actual paths pkgsrc is configured to use. This struct is created
/// after sandbox setup and passed to build operations.
#[derive(Clone, Debug)]
pub struct PkgsrcEnv {
    /// PACKAGES directory for binary packages.
    pub packages: PathBuf,
    /// PKG_TOOLS_BIN directory containing pkg_add, pkg_delete, etc.
    pub pkgtools: PathBuf,
    /// PREFIX installation directory.
    pub prefix: PathBuf,
    /// PKG_DBDIR for installed package database.
    pub pkg_dbdir: PathBuf,
    /// PKG_REFCOUNT_DBDIR for refcounted files database.
    pub pkg_refcount_dbdir: PathBuf,
    /// Cached pkgsrc variables from the `cachevars` config option.
    pub cachevars: HashMap<String, String>,
}

impl PkgsrcEnv {
    /// Fetch pkgsrc environment variables by querying bmake.
    ///
    /// This must be called after sandbox 0 is created if sandboxes are enabled,
    /// since bmake may only exist inside the sandbox.
    pub fn fetch(config: &Config, sandbox: &Sandbox, id: Option<usize>) -> Result<Self> {
        const REQUIRED_VARS: &[&str] = &[
            "PACKAGES",
            "PKG_DBDIR",
            "PKG_REFCOUNT_DBDIR",
            "PKG_TOOLS_BIN",
            "PREFIX",
        ];

        let user_cachevars = config.cachevars();
        let mut all_varnames: Vec<&str> = REQUIRED_VARS.to_vec();
        for v in user_cachevars {
            all_varnames.push(v.as_str());
        }

        let varnames_arg = all_varnames.join(" ");
        let script = format!(
            "cd {}/pkgtools/pkg_install && {} show-vars VARNAMES=\"{}\"\n",
            config.pkgsrc().display(),
            config.make().display(),
            varnames_arg
        );

        let child = sandbox.execute_script(id, &script, vec![])?;
        let output = child
            .wait_with_output()
            .context("Failed to execute bmake show-vars")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!("Failed to query pkgsrc variables: {}", stderr.trim());
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let lines: Vec<&str> = stdout.lines().collect();

        if lines.len() != all_varnames.len() {
            bail!(
                "Expected {} variables from pkgsrc, got {}",
                all_varnames.len(),
                lines.len()
            );
        }

        let mut values: HashMap<&str, &str> = HashMap::new();
        for (varname, value) in all_varnames.iter().zip(&lines) {
            values.insert(varname, value);
        }

        for varname in REQUIRED_VARS {
            if values.get(varname).is_none_or(|v| v.is_empty()) {
                bail!("pkgsrc returned empty value for {}", varname);
            }
        }

        let mut cachevars: HashMap<String, String> = HashMap::new();
        for varname in user_cachevars {
            if let Some(value) = values.get(varname.as_str()) {
                if !value.is_empty() {
                    cachevars.insert(varname.clone(), (*value).to_string());
                }
            }
        }

        Ok(PkgsrcEnv {
            packages: PathBuf::from(values["PACKAGES"]),
            pkgtools: PathBuf::from(values["PKG_TOOLS_BIN"]),
            prefix: PathBuf::from(values["PREFIX"]),
            pkg_dbdir: PathBuf::from(values["PKG_DBDIR"]),
            pkg_refcount_dbdir: PathBuf::from(values["PKG_REFCOUNT_DBDIR"]),
            cachevars,
        })
    }
}

/// Holds the Lua state for evaluating env functions.
#[derive(Clone)]
pub struct LuaEnv {
    lua: Arc<Mutex<Lua>>,
    env_key: Option<Arc<RegistryKey>>,
}

impl std::fmt::Debug for LuaEnv {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LuaEnv")
            .field("has_env", &self.env_key.is_some())
            .finish()
    }
}

impl Default for LuaEnv {
    fn default() -> Self {
        Self {
            lua: Arc::new(Mutex::new(Lua::new())),
            env_key: None,
        }
    }
}

impl LuaEnv {
    /// Get environment variables for a package by calling the env function.
    /// Returns a HashMap of VAR_NAME -> value.
    pub fn get_env(&self, pkg: &ResolvedPackage) -> Result<HashMap<String, String>, String> {
        let Some(env_key) = &self.env_key else {
            return Ok(HashMap::new());
        };

        let lua = self
            .lua
            .lock()
            .map_err(|e| format!("Lua lock error: {}", e))?;

        // Get the env value from registry
        let env_value: Value = lua
            .registry_value(env_key)
            .map_err(|e| format!("Failed to get env from registry: {}", e))?;

        let idx = &pkg.index;

        let result_table: Table = match env_value {
            // If it's a function, call it with pkg info
            Value::Function(func) => {
                let pkg_table = lua
                    .create_table()
                    .map_err(|e| format!("Failed to create table: {}", e))?;

                // Set all ScanIndex fields
                pkg_table
                    .set("pkgname", idx.pkgname.to_string())
                    .map_err(|e| format!("Failed to set pkgname: {}", e))?;
                pkg_table
                    .set("pkgpath", pkg.pkgpath.as_path().display().to_string())
                    .map_err(|e| format!("Failed to set pkgpath: {}", e))?;
                pkg_table
                    .set(
                        "all_depends",
                        idx.all_depends
                            .as_ref()
                            .map(|deps| {
                                deps.depends()
                                    .filter_map(|d| d.ok())
                                    .map(|d| d.pkgpath().to_string())
                                    .collect::<Vec<_>>()
                                    .join(" ")
                            })
                            .unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set all_depends: {}", e))?;
                pkg_table
                    .set(
                        "pkg_skip_reason",
                        idx.pkg_skip_reason.clone().unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set pkg_skip_reason: {}", e))?;
                pkg_table
                    .set(
                        "pkg_fail_reason",
                        idx.pkg_fail_reason.clone().unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set pkg_fail_reason: {}", e))?;
                pkg_table
                    .set(
                        "no_bin_on_ftp",
                        idx.no_bin_on_ftp.clone().unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set no_bin_on_ftp: {}", e))?;
                pkg_table
                    .set("restricted", idx.restricted.clone().unwrap_or_default())
                    .map_err(|e| format!("Failed to set restricted: {}", e))?;
                pkg_table
                    .set("categories", idx.categories.clone().unwrap_or_default())
                    .map_err(|e| format!("Failed to set categories: {}", e))?;
                pkg_table
                    .set("maintainer", idx.maintainer.clone().unwrap_or_default())
                    .map_err(|e| format!("Failed to set maintainer: {}", e))?;
                pkg_table
                    .set("use_destdir", idx.use_destdir.clone().unwrap_or_default())
                    .map_err(|e| format!("Failed to set use_destdir: {}", e))?;
                pkg_table
                    .set(
                        "bootstrap_pkg",
                        idx.bootstrap_pkg.clone().unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set bootstrap_pkg: {}", e))?;
                pkg_table
                    .set(
                        "usergroup_phase",
                        idx.usergroup_phase.clone().unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set usergroup_phase: {}", e))?;
                pkg_table
                    .set(
                        "scan_depends",
                        idx.scan_depends
                            .as_ref()
                            .map(|deps| {
                                deps.iter()
                                    .map(|p| p.display().to_string())
                                    .collect::<Vec<_>>()
                                    .join(" ")
                            })
                            .unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set scan_depends: {}", e))?;
                pkg_table
                    .set("pbulk_weight", idx.pbulk_weight.clone().unwrap_or_default())
                    .map_err(|e| format!("Failed to set pbulk_weight: {}", e))?;
                pkg_table
                    .set(
                        "multi_version",
                        idx.multi_version
                            .as_ref()
                            .map(|v| v.join(" "))
                            .unwrap_or_default(),
                    )
                    .map_err(|e| format!("Failed to set multi_version: {}", e))?;
                pkg_table
                    .set(
                        "depends",
                        pkg.depends()
                            .iter()
                            .map(|d| d.to_string())
                            .collect::<Vec<_>>()
                            .join(" "),
                    )
                    .map_err(|e| format!("Failed to set depends: {}", e))?;

                func.call(pkg_table)
                    .map_err(|e| format!("Failed to call env function: {}", e))?
            }
            // If it's a table, use it directly
            Value::Table(t) => t,
            Value::Nil => return Ok(HashMap::new()),
            _ => return Err("env must be a function or table".to_string()),
        };

        // Convert Lua table to HashMap
        let mut env = HashMap::new();
        for pair in result_table.pairs::<String, String>() {
            let (k, v) = pair.map_err(|e| format!("Failed to iterate env table: {}", e))?;
            env.insert(k, v);
        }

        Ok(env)
    }
}

/// Main configuration structure.
#[derive(Clone, Debug, Default)]
pub struct Config {
    file: ConfigFile,
    dbdir: PathBuf,
    logdir: PathBuf,
    log_level: String,
    lua_env: LuaEnv,
}

/// Parsed configuration file contents.
#[derive(Clone, Debug, Default)]
pub struct ConfigFile {
    /// The `options` section.
    pub options: Option<Options>,
    /// The `pkgsrc` section.
    pub pkgsrc: Pkgsrc,
    /// The `scripts` section (script name -> path).
    pub scripts: HashMap<String, PathBuf>,
    /// The `sandboxes` section.
    pub sandboxes: Option<Sandboxes>,
    /// The `environment` section.
    pub environment: Option<Environment>,
    /// The `dynamic` section.
    pub dynamic: Option<DynamicConfig>,
}

/// General build options from the `options` section.
///
/// All fields are optional; defaults are used when not specified:
/// - `build_threads`: 1
/// - `scan_threads`: 1
/// - `log_level`: "info"
#[derive(Clone, Debug, Default)]
pub struct Options {
    /// Number of parallel build sandboxes.
    pub build_threads: Option<usize>,
    /// Directory for bob state files (database, tracing log).
    pub dbdir: Option<PathBuf>,
    /// Number of parallel scan processes.
    pub scan_threads: Option<usize>,
    /// If true, abort on scan errors. If false, continue and report failures.
    pub strict_scan: Option<bool>,
    /// Log level: "trace", "debug", "info", "warn", or "error".
    pub log_level: Option<String>,
    /// Enable TUI progress display (default: true). Set to false for plain output.
    pub tui: Option<bool>,
}

/// Dynamic resource allocation from the `dynamic` section.
///
/// Controls dynamic CPU and disk allocation informed by build history.
///
/// - `jobs`: Total MAKE_JOBS budget to distribute across concurrent builds.
///   Set this to the number of available CPU threads.  The allocator will
///   slightly over-allocate to ensure optimal throughput during serial
///   build phases.
/// - `wrkobjdir`: Optional automatic WRKOBJDIR selection based on historical
///   disk usage, routing large builds to disk and small builds to tmpfs.
#[derive(Clone, Debug)]
pub struct DynamicConfig {
    /// Total MAKE_JOBS budget.
    pub jobs: Option<usize>,
    /// Optional WRKOBJDIR routing based on historical disk usage.
    pub wrkobjdir: Option<WrkObjDir>,
}

/// WRKOBJDIR routing configuration.
///
/// When both `tmpfs` and `disk` are set with a `threshold`, packages
/// whose historical disk usage exceeds `threshold` build in `disk`
/// and everything else builds in `tmpfs`.  When only one path is set,
/// all builds use that path.
#[derive(Clone, Debug)]
pub struct WrkObjDir {
    /// Fast (tmpfs) WRKOBJDIR for builds under threshold.
    pub tmpfs: Option<PathBuf>,
    /// Disk-backed WRKOBJDIR for large builds.
    pub disk: Option<PathBuf>,
    /// Size threshold in bytes for routing between tmpfs and disk.
    pub threshold: Option<u64>,
}

impl WrkObjDir {
    /// Route a package to tmpfs or disk based on historical disk usage.
    pub fn route(&self, disk_usage: Option<u64>) -> Option<WrkObjKind> {
        match (&self.tmpfs, &self.disk, self.threshold) {
            (Some(tmpfs), Some(disk), Some(threshold)) => match disk_usage {
                Some(size) if size <= threshold => Some(WrkObjKind::Tmpfs(tmpfs.clone())),
                _ => Some(WrkObjKind::Disk(disk.clone())),
            },
            (Some(dir), None, _) => Some(WrkObjKind::Tmpfs(dir.clone())),
            (None, Some(dir), _) => Some(WrkObjKind::Disk(dir.clone())),
            _ => None,
        }
    }
}

/**
 * A resolved WRKOBJDIR assignment for a single package.
 */
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum WrkObjKind {
    Tmpfs(PathBuf),
    Disk(PathBuf),
}

impl WrkObjKind {
    pub fn path(&self) -> &Path {
        match self {
            Self::Tmpfs(p) | Self::Disk(p) => p,
        }
    }
}

/// pkgsrc-related configuration from the `pkgsrc` section.
///
/// # Required Fields
///
/// - `basedir`: Path to pkgsrc source tree
/// - `make`: Path to bmake binary
///
/// # Optional Fields
///
/// - `bootstrap`: Path to bootstrap tarball (required on non-NetBSD systems)
/// - `build_user`: Unprivileged user for builds
/// - `logdir`: Directory for build logs (defaults to `dbdir/logs`)
/// - `pkgpaths`: List of packages to build
/// - `save_wrkdir_patterns`: Glob patterns for files to save on build failure
/// - `tar`: Path to tar binary (defaults to `tar`)
#[derive(Clone, Debug, Default)]
pub struct Pkgsrc {
    /// Path to pkgsrc source tree.
    pub basedir: PathBuf,
    /// Path to bootstrap tarball (required on non-NetBSD).
    pub bootstrap: Option<PathBuf>,
    /// Unprivileged user for builds.
    pub build_user: Option<String>,
    /// Home directory of build_user (resolved from password database).
    pub build_user_home: Option<PathBuf>,
    /// Directory for build logs (defaults to dbdir/logs).
    pub logdir: Option<PathBuf>,
    /// Path to bmake binary.
    pub make: PathBuf,
    /// List of packages to build.
    pub pkgpaths: Option<Vec<PkgPath>>,
    /// Glob patterns for files to save from WRKDIR on failure.
    pub save_wrkdir_patterns: Vec<String>,
    /// pkgsrc variables to cache and re-set in each environment run.
    pub cachevars: Vec<String>,
    /// Path to tar binary (defaults to `tar` in PATH).
    pub tar: Option<PathBuf>,
}

/// Environment configuration from the `environment` section.
///
/// Controls the environment variables available to sandbox processes.
///
/// If this section is omitted from the config, the parent environment is
/// inherited unchanged.  If present, `clear` defaults to true and the
/// environment is cleared before applying the configured variables.
///
/// # Example
///
/// ```lua
/// environment = {
///     inherit = { "TERM", "HOME" },
///     set = {
///         PATH = "/sbin:/bin:/usr/sbin:/usr/bin",
///     },
/// }
/// ```
#[derive(Clone, Debug)]
pub struct Environment {
    /// If true (default), clear the environment before setting variables.
    /// If false, inherit the full parent environment.
    pub clear: bool,
    /// Variable names to copy from the parent environment (when `clear = true`).
    pub inherit: Vec<String>,
    /// Variables to set explicitly.
    pub set: HashMap<String, String>,
}

impl Default for Environment {
    fn default() -> Self {
        Self {
            clear: true,
            inherit: Vec::new(),
            set: HashMap::new(),
        }
    }
}

/// Sandbox configuration from the `sandboxes` section.
///
/// When this section is present in the configuration, builds are performed
/// in isolated chroot environments.
///
/// # Example
///
/// ```lua
/// sandboxes = {
///     basedir = "/data/chroot",
///     actions = {
///         { action = "mount", fs = "proc", dir = "/proc" },
///         { action = "copy", dir = "/etc" },
///     },
/// }
/// ```
#[derive(Clone, Debug, Default)]
pub struct Sandboxes {
    /// Base directory for sandbox roots (e.g., `/data/chroot`).
    ///
    /// Individual sandboxes are created as numbered subdirectories:
    /// `basedir/0`, `basedir/1`, etc.
    pub basedir: PathBuf,
    /// Actions to perform during sandbox setup/teardown.
    ///
    /// See [`Action`] for details.
    pub actions: Vec<Action>,
    /// Path to bindfs binary (defaults to "bindfs").
    pub bindfs: String,
}

impl Config {
    /// Load configuration from a Lua file.
    ///
    /// # Arguments
    ///
    /// * `config_path` - Path to configuration file, or `None` to use `./config.lua`
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration file doesn't exist or contains
    /// invalid Lua syntax.
    pub fn load(config_path: Option<&Path>) -> Result<Config> {
        /*
         * Load user-supplied configuration file, or the default location.
         */
        let filename = if let Some(path) = config_path {
            if path.is_relative() {
                std::env::current_dir()
                    .context("Unable to determine current directory")?
                    .join(path)
            } else {
                path.to_path_buf()
            }
        } else {
            std::env::current_dir()
                .context("Unable to determine current directory")?
                .join("config.lua")
        };

        /* A configuration file is mandatory. */
        if !filename.exists() {
            anyhow::bail!("Configuration file {} does not exist", filename.display());
        }

        /*
         * Parse configuration file as Lua.
         */
        let (mut file, lua_env) =
            load_lua(&filename)
                .map_err(|e| anyhow!(e))
                .with_context(|| {
                    format!(
                        "Unable to parse Lua configuration file {}",
                        filename.display()
                    )
                })?;

        /*
         * Parse scripts section.  Paths are resolved relative to config dir
         * if not absolute.
         */
        let base_dir = filename.parent().unwrap_or_else(|| Path::new("."));
        let mut newscripts: HashMap<String, PathBuf> = HashMap::new();
        for (k, v) in &file.scripts {
            let fullpath = if v.is_relative() {
                base_dir.join(v)
            } else {
                v.clone()
            };
            newscripts.insert(k.clone(), fullpath);
        }
        file.scripts = newscripts;

        /*
         * Validate bootstrap path exists if specified.
         */
        if let Some(ref bootstrap) = file.pkgsrc.bootstrap {
            if !bootstrap.exists() {
                anyhow::bail!(
                    "pkgsrc.bootstrap file {} does not exist",
                    bootstrap.display()
                );
            }
        }

        /*
         * Resolve dbdir: explicit value from options, or default to
         * "./db" relative to the config file directory.  Relative paths
         * are resolved against the config directory.
         */
        let raw_dbdir = file.options.as_ref().and_then(|o| o.dbdir.clone());
        let dbdir = match raw_dbdir {
            Some(p) if p.is_absolute() => p,
            Some(p) => base_dir.join(p),
            None => base_dir.join("db"),
        };

        /*
         * Default logdir to dbdir/logs if not explicitly set.
         */
        let logdir = file
            .pkgsrc
            .logdir
            .clone()
            .unwrap_or_else(|| dbdir.join("logs"));

        /*
         * Set log_level from config file, defaulting to "info".
         */
        let log_level = if let Some(opts) = &file.options {
            opts.log_level.clone().unwrap_or_else(|| "info".to_string())
        } else {
            "info".to_string()
        };

        Ok(Config {
            file,
            dbdir,
            logdir,
            log_level,
            lua_env,
        })
    }

    pub fn build_threads(&self) -> usize {
        if let Some(opts) = &self.file.options {
            opts.build_threads.unwrap_or(1)
        } else {
            1
        }
    }

    pub fn scan_threads(&self) -> usize {
        if let Some(opts) = &self.file.options {
            opts.scan_threads.unwrap_or(1)
        } else {
            1
        }
    }

    pub fn strict_scan(&self) -> bool {
        if let Some(opts) = &self.file.options {
            opts.strict_scan.unwrap_or(false)
        } else {
            false
        }
    }

    pub fn jobs(&self) -> Option<usize> {
        self.file.dynamic.as_ref().and_then(|s| s.jobs)
    }

    pub fn wrkobjdir(&self) -> Option<&WrkObjDir> {
        self.file
            .dynamic
            .as_ref()
            .and_then(|s| s.wrkobjdir.as_ref())
    }

    pub fn script(&self, key: &str) -> Option<&PathBuf> {
        self.file.scripts.get(key)
    }

    pub fn make(&self) -> &PathBuf {
        &self.file.pkgsrc.make
    }

    pub fn pkgpaths(&self) -> &Option<Vec<PkgPath>> {
        &self.file.pkgsrc.pkgpaths
    }

    pub fn pkgsrc(&self) -> &PathBuf {
        &self.file.pkgsrc.basedir
    }

    pub fn sandboxes(&self) -> &Option<Sandboxes> {
        &self.file.sandboxes
    }

    pub fn environment(&self) -> Option<&Environment> {
        self.file.environment.as_ref()
    }

    pub fn bindfs(&self) -> &str {
        self.file
            .sandboxes
            .as_ref()
            .map(|s| s.bindfs.as_str())
            .unwrap_or("bindfs")
    }

    pub fn log_level(&self) -> &str {
        &self.log_level
    }

    pub fn tui(&self) -> bool {
        self.file
            .options
            .as_ref()
            .and_then(|o| o.tui)
            .unwrap_or(true)
    }

    pub fn dbdir(&self) -> &PathBuf {
        &self.dbdir
    }

    pub fn logdir(&self) -> &PathBuf {
        &self.logdir
    }

    pub fn save_wrkdir_patterns(&self) -> &[String] {
        self.file.pkgsrc.save_wrkdir_patterns.as_slice()
    }

    pub fn tar(&self) -> Option<&PathBuf> {
        self.file.pkgsrc.tar.as_ref()
    }

    pub fn build_user(&self) -> Option<&str> {
        self.file.pkgsrc.build_user.as_deref()
    }

    pub fn build_user_home(&self) -> Option<&Path> {
        self.file.pkgsrc.build_user_home.as_deref()
    }

    pub fn bootstrap(&self) -> Option<&PathBuf> {
        self.file.pkgsrc.bootstrap.as_ref()
    }

    /// Return list of pkgsrc variable names to cache.
    pub fn cachevars(&self) -> &[String] {
        self.file.pkgsrc.cachevars.as_slice()
    }

    /// Get environment variables for a package from the Lua env function/table.
    pub fn get_pkg_env(
        &self,
        pkg: &ResolvedPackage,
    ) -> Result<std::collections::HashMap<String, String>, String> {
        self.lua_env.get_env(pkg)
    }

    /// Return environment variables for script execution.
    ///
    /// If `pkgsrc_env` is provided, includes the pkgsrc-derived variables
    /// (packages, pkgtools, prefix, pkg_dbdir, pkg_refcount_dbdir).
    /// Return environment variables for script execution.
    ///
    /// If `pkgsrc_env` is provided, includes the pkgsrc-derived variables
    /// (packages, pkgtools, prefix, pkg_dbdir, pkg_refcount_dbdir) as well
    /// as the cached variables from the `cachevars` config option.
    pub fn script_env(&self, pkgsrc_env: Option<&PkgsrcEnv>) -> Vec<(String, String)> {
        let mut envs = vec![
            (
                "bob_logdir".to_string(),
                format!("{}", self.logdir().display()),
            ),
            ("bob_make".to_string(), format!("{}", self.make().display())),
            (
                "bob_pkgsrc".to_string(),
                format!("{}", self.pkgsrc().display()),
            ),
        ];
        if let Some(env) = pkgsrc_env {
            envs.push((
                "bob_packages".to_string(),
                env.packages.display().to_string(),
            ));
            envs.push((
                "bob_pkgtools".to_string(),
                env.pkgtools.display().to_string(),
            ));
            envs.push(("bob_prefix".to_string(), env.prefix.display().to_string()));
            envs.push((
                "bob_pkg_dbdir".to_string(),
                env.pkg_dbdir.display().to_string(),
            ));
            envs.push((
                "bob_pkg_refcount_dbdir".to_string(),
                env.pkg_refcount_dbdir.display().to_string(),
            ));
            for (key, value) in &env.cachevars {
                envs.push((key.clone(), value.clone()));
            }
        }
        let tar_value = self
            .tar()
            .map(|t| t.display().to_string())
            .unwrap_or_else(|| "tar".to_string());
        envs.push(("bob_tar".to_string(), tar_value));
        if let Some(build_user) = self.build_user() {
            envs.push(("bob_build_user".to_string(), build_user.to_string()));
        }
        if let Some(home) = self.build_user_home() {
            envs.push((
                "bob_build_user_home".to_string(),
                home.display().to_string(),
            ));
        }
        if let Some(bootstrap) = self.bootstrap() {
            envs.push((
                "bob_bootstrap".to_string(),
                format!("{}", bootstrap.display()),
            ));
        }
        envs
    }

    /// Validate the configuration, checking that required paths and files exist.
    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors: Vec<String> = Vec::new();

        // Check pkgsrc directory exists
        if !self.file.pkgsrc.basedir.exists() {
            errors.push(format!(
                "pkgsrc basedir does not exist: {}",
                self.file.pkgsrc.basedir.display()
            ));
        }

        // Check make binary exists (only on host if sandboxes not enabled)
        // When sandboxes are enabled, the make binary is inside the sandbox
        if self.file.sandboxes.is_none() && !self.file.pkgsrc.make.exists() {
            errors.push(format!(
                "make binary does not exist: {}",
                self.file.pkgsrc.make.display()
            ));
        }

        // Check scripts exist
        for (name, path) in &self.file.scripts {
            if !path.exists() {
                errors.push(format!(
                    "Script '{}' does not exist: {}",
                    name,
                    path.display()
                ));
            } else if !path.is_file() {
                errors.push(format!(
                    "Script '{}' is not a file: {}",
                    name,
                    path.display()
                ));
            }
        }

        // Check sandbox basedir is writable if sandboxes enabled
        if let Some(sandboxes) = &self.file.sandboxes {
            // Check parent directory exists or can be created
            if let Some(parent) = sandboxes.basedir.parent() {
                if !parent.exists() {
                    errors.push(format!(
                        "Sandbox basedir parent does not exist: {}",
                        parent.display()
                    ));
                }
            }
        }

        // Check dbdir can be created
        if let Some(parent) = self.dbdir.parent() {
            if !parent.exists() {
                errors.push(format!(
                    "dbdir parent directory does not exist: {}",
                    parent.display()
                ));
            }
        }

        // Thread counts must be at least 1
        if let Some(opts) = &self.file.options {
            if opts.build_threads == Some(0) {
                errors.push("build_threads must be at least 1".to_string());
            }
            if opts.scan_threads == Some(0) {
                errors.push("scan_threads must be at least 1".to_string());
            }
        }

        // Dynamic resource allocation validation
        if let Some(dyn_cfg) = &self.file.dynamic {
            if dyn_cfg.jobs == Some(0) {
                errors.push("dynamic.jobs must be at least 1".to_string());
            }
            if let Some(w) = &dyn_cfg.wrkobjdir {
                if w.tmpfs.is_none() && w.disk.is_none() {
                    errors.push(
                        "dynamic.wrkobjdir requires at least one of tmpfs or disk".to_string(),
                    );
                }
                if w.tmpfs.is_some() && w.disk.is_some() && w.threshold.is_none() {
                    errors.push(
                        "dynamic.wrkobjdir.threshold is required when both \
                         tmpfs and disk are set"
                            .to_string(),
                    );
                }
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

/// Load a Lua configuration file and return a ConfigFile and LuaEnv.
fn load_lua(filename: &Path) -> Result<(ConfigFile, LuaEnv), String> {
    let lua = Lua::new();

    // Add config directory to package.path so require() finds relative modules
    if let Some(config_dir) = filename.parent() {
        let globals = lua.globals();
        let pkg: Table = globals
            .get("package")
            .map_err(|e| format!("Failed to get package table: {}", e))?;
        let existing: String = pkg
            .get("path")
            .map_err(|e| format!("Failed to get package.path: {}", e))?;
        let new_path = format!("{}/?.lua;{}", config_dir.display(), existing);
        pkg.set("path", new_path)
            .map_err(|e| format!("Failed to set package.path: {}", e))?;
    }

    // Load built-in helper functions
    lua.load(include_str!("funcs.lua"))
        .exec()
        .map_err(|e| format!("Failed to load helper functions: {}", e))?;

    lua.load(filename)
        .exec()
        .map_err(|e| format!("Lua execution error: {}", e))?;

    // Get the global table (Lua script should set global variables)
    let globals = lua.globals();

    // Parse each section
    let options =
        parse_options(&globals).map_err(|e| format!("Error parsing options config: {}", e))?;
    let pkgsrc_table: Table = globals
        .get("pkgsrc")
        .map_err(|e| format!("Error getting pkgsrc config: {}", e))?;
    let pkgsrc =
        parse_pkgsrc(&globals).map_err(|e| format!("Error parsing pkgsrc config: {}", e))?;
    let scripts =
        parse_scripts(&globals).map_err(|e| format!("Error parsing scripts config: {}", e))?;
    let sandboxes =
        parse_sandboxes(&globals).map_err(|e| format!("Error parsing sandboxes config: {}", e))?;
    let environment = parse_environment(&globals)
        .map_err(|e| format!("Error parsing environment config: {}", e))?;
    let dynamic =
        parse_dynamic(&globals).map_err(|e| format!("Error parsing dynamic config: {}", e))?;

    // Store env function/table in registry if it exists
    let env_key = if let Ok(env_value) = pkgsrc_table.get::<Value>("env") {
        if !env_value.is_nil() {
            let key = lua
                .create_registry_value(env_value)
                .map_err(|e| format!("Failed to store env in registry: {}", e))?;
            Some(Arc::new(key))
        } else {
            None
        }
    } else {
        None
    };

    let lua_env = LuaEnv {
        lua: Arc::new(Mutex::new(lua)),
        env_key,
    };

    let config = ConfigFile {
        options,
        pkgsrc,
        scripts,
        sandboxes,
        environment,
        dynamic,
    };

    Ok((config, lua_env))
}

fn parse_options(globals: &Table) -> LuaResult<Option<Options>> {
    let options: Value = globals.get("options")?;
    if options.is_nil() {
        return Ok(None);
    }

    let table = options
        .as_table()
        .ok_or_else(|| mlua::Error::runtime("'options' must be a table"))?;

    const KNOWN_KEYS: &[&str] = &[
        "build_threads",
        "dbdir",
        "log_level",
        "scan_threads",
        "tui",
        "strict_scan",
    ];
    warn_unknown_keys(table, "options", KNOWN_KEYS);

    let dbdir: Option<PathBuf> = table.get::<Option<String>>("dbdir")?.map(PathBuf::from);

    Ok(Some(Options {
        build_threads: table.get::<Option<usize>>("build_threads")?,
        dbdir,
        scan_threads: table.get::<Option<usize>>("scan_threads")?,
        strict_scan: table.get::<Option<bool>>("strict_scan")?,
        log_level: table.get::<Option<String>>("log_level")?,
        tui: table.get::<Option<bool>>("tui")?,
    }))
}

/// Warn about unknown keys in a Lua table.
fn warn_unknown_keys(table: &Table, table_name: &str, known_keys: &[&str]) {
    for (key, _) in table.pairs::<String, Value>().flatten() {
        if !known_keys.contains(&key.as_str()) {
            eprintln!("Warning: unknown config key '{}.{}'", table_name, key);
        }
    }
}

fn get_required_string(table: &Table, field: &str) -> LuaResult<String> {
    let value: Value = table.get(field)?;
    match value {
        Value::String(s) => Ok(s.to_str()?.to_string()),
        Value::Integer(n) => Ok(n.to_string()),
        Value::Number(n) => Ok(n.to_string()),
        Value::Nil => Err(mlua::Error::runtime(format!(
            "missing required field '{}'",
            field
        ))),
        _ => Err(mlua::Error::runtime(format!(
            "field '{}' must be a string, got {}",
            field,
            value.type_name()
        ))),
    }
}

/// Parse a human-readable size string into bytes.
///
/// Accepts integer suffixes K, M, G, T (case-insensitive) with optional
/// fractional parts (e.g. "1.5G"), or bare byte counts.
fn parse_size(s: &str) -> Result<u64, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty size string".to_string());
    }

    let (num_str, multiplier) = match s.as_bytes().last() {
        Some(b'K' | b'k') => (&s[..s.len() - 1], 1024u64),
        Some(b'M' | b'm') => (&s[..s.len() - 1], 1024u64 * 1024),
        Some(b'G' | b'g') => (&s[..s.len() - 1], 1024u64 * 1024 * 1024),
        Some(b'T' | b't') => (&s[..s.len() - 1], 1024u64 * 1024 * 1024 * 1024),
        _ => (s, 1u64),
    };

    if multiplier > 1 {
        let n: f64 = num_str
            .parse()
            .map_err(|_| format!("invalid size: '{}'", s))?;
        if n < 0.0 {
            return Err(format!("negative size: '{}'", s));
        }
        Ok((n * multiplier as f64) as u64)
    } else {
        s.parse::<u64>()
            .map_err(|_| format!("invalid size: '{}'", s))
    }
}

/**
 * Look up a user's home directory from the password database.
 */
fn get_home_dir(username: &str) -> Result<PathBuf, String> {
    let cname = CString::new(username).map_err(|_| format!("invalid username: '{}'", username))?;
    // SAFETY: getpwnam is called with a valid C string.
    let pw = unsafe { libc::getpwnam(cname.as_ptr()) };
    if pw.is_null() {
        return Err(format!(
            "user '{}' not found in password database",
            username
        ));
    }
    // SAFETY: pw is non-null and pw_dir is a valid C string.
    let home = unsafe { CStr::from_ptr((*pw).pw_dir) };
    let path = home
        .to_str()
        .map_err(|_| format!("non-UTF-8 home directory for user '{}'", username))?;
    Ok(PathBuf::from(path))
}

fn parse_dynamic(globals: &Table) -> LuaResult<Option<DynamicConfig>> {
    let value: Value = globals.get("dynamic")?;
    if value.is_nil() {
        return Ok(None);
    }

    let table = value
        .as_table()
        .ok_or_else(|| mlua::Error::runtime("'dynamic' must be a table"))?;

    const KNOWN_KEYS: &[&str] = &["jobs", "wrkobjdir"];
    warn_unknown_keys(table, "dynamic", KNOWN_KEYS);

    let jobs: Option<usize> = table.get::<Option<usize>>("jobs")?;

    let wrkobjdir = match table.get::<Value>("wrkobjdir")? {
        Value::Nil => None,
        Value::Table(t) => {
            const WRK_KEYS: &[&str] = &["tmpfs", "disk", "threshold"];
            warn_unknown_keys(&t, "dynamic.wrkobjdir", WRK_KEYS);

            let tmpfs: Option<PathBuf> = t.get::<Option<String>>("tmpfs")?.map(PathBuf::from);
            let disk: Option<PathBuf> = t.get::<Option<String>>("disk")?.map(PathBuf::from);
            let threshold: Option<u64> = t
                .get::<Option<String>>("threshold")?
                .map(|s| {
                    parse_size(&s).map_err(|e| {
                        mlua::Error::runtime(format!("dynamic.wrkobjdir.threshold: {}", e))
                    })
                })
                .transpose()?;

            Some(WrkObjDir {
                tmpfs,
                disk,
                threshold,
            })
        }
        _ => return Err(mlua::Error::runtime("dynamic.wrkobjdir must be a table")),
    };

    Ok(Some(DynamicConfig { jobs, wrkobjdir }))
}

fn parse_pkgsrc(globals: &Table) -> LuaResult<Pkgsrc> {
    let pkgsrc: Table = globals.get("pkgsrc")?;

    const KNOWN_KEYS: &[&str] = &[
        "basedir",
        "bootstrap",
        "build_user",
        "build_user_home",
        "cachevars",
        "env",
        "logdir",
        "make",
        "pkgpaths",
        "save_wrkdir_patterns",
        "tar",
    ];
    warn_unknown_keys(&pkgsrc, "pkgsrc", KNOWN_KEYS);

    let basedir = get_required_string(&pkgsrc, "basedir")?;
    let bootstrap: Option<PathBuf> = pkgsrc
        .get::<Option<String>>("bootstrap")?
        .map(PathBuf::from);
    let build_user: Option<String> = pkgsrc.get::<Option<String>>("build_user")?;
    let build_user_home = if let Some(ref user) = build_user {
        if let Some(explicit) = pkgsrc.get::<Option<String>>("build_user_home")? {
            Some(PathBuf::from(explicit))
        } else {
            let home = get_home_dir(user)
                .map_err(|e| mlua::Error::runtime(format!("pkgsrc.build_user: {}", e)))?;
            pkgsrc.set("build_user_home", home.display().to_string())?;
            Some(home)
        }
    } else {
        None
    };
    let logdir: Option<PathBuf> = pkgsrc.get::<Option<String>>("logdir")?.map(PathBuf::from);
    let make = get_required_string(&pkgsrc, "make")?;
    let tar: Option<PathBuf> = pkgsrc.get::<Option<String>>("tar")?.map(PathBuf::from);

    let pkgpaths: Option<Vec<PkgPath>> = match pkgsrc.get::<Value>("pkgpaths")? {
        Value::Nil => None,
        Value::Table(t) => {
            let mut paths = Vec::new();
            for (i, val) in t.sequence_values::<Value>().enumerate() {
                let val = val.map_err(|e| {
                    mlua::Error::runtime(format!("pkgsrc.pkgpaths[{}]: {}", i + 1, e))
                })?;
                let Value::String(s) = val else {
                    return Err(mlua::Error::runtime(format!(
                        "pkgsrc.pkgpaths[{}]: expected string",
                        i + 1
                    )));
                };
                let s = s.to_str().map_err(|e| {
                    mlua::Error::runtime(format!("pkgsrc.pkgpaths[{}]: {}", i + 1, e))
                })?;
                match PkgPath::new(&s) {
                    Ok(p) => paths.push(p),
                    Err(e) => {
                        return Err(mlua::Error::runtime(format!(
                            "pkgsrc.pkgpaths[{}]: invalid pkgpath '{}': {}",
                            i + 1,
                            s,
                            e
                        )));
                    }
                }
            }
            if paths.is_empty() { None } else { Some(paths) }
        }
        _ => None,
    };

    let save_wrkdir_patterns: Vec<String> = match pkgsrc.get::<Value>("save_wrkdir_patterns")? {
        Value::Nil => Vec::new(),
        Value::Table(t) => t
            .sequence_values::<String>()
            .filter_map(|r| r.ok())
            .collect(),
        _ => Vec::new(),
    };

    let cachevars: Vec<String> = match pkgsrc.get::<Value>("cachevars")? {
        Value::Nil => Vec::new(),
        Value::Table(t) => t
            .sequence_values::<String>()
            .filter_map(|r| r.ok())
            .collect(),
        _ => Vec::new(),
    };

    Ok(Pkgsrc {
        basedir: PathBuf::from(basedir),
        bootstrap,
        build_user,
        build_user_home,
        cachevars,
        logdir,
        make: PathBuf::from(make),
        pkgpaths,
        save_wrkdir_patterns,
        tar,
    })
}

fn parse_scripts(globals: &Table) -> LuaResult<HashMap<String, PathBuf>> {
    let scripts: Value = globals.get("scripts")?;
    if scripts.is_nil() {
        return Ok(HashMap::new());
    }

    let table = scripts
        .as_table()
        .ok_or_else(|| mlua::Error::runtime("'scripts' must be a table"))?;

    let mut result = HashMap::new();
    for pair in table.pairs::<String, String>() {
        let (k, v) = pair?;
        result.insert(k, PathBuf::from(v));
    }

    Ok(result)
}

fn parse_sandboxes(globals: &Table) -> LuaResult<Option<Sandboxes>> {
    let sandboxes: Value = globals.get("sandboxes")?;
    if sandboxes.is_nil() {
        return Ok(None);
    }

    let table = sandboxes
        .as_table()
        .ok_or_else(|| mlua::Error::runtime("'sandboxes' must be a table"))?;

    const KNOWN_KEYS: &[&str] = &["actions", "basedir", "bindfs"];
    warn_unknown_keys(table, "sandboxes", KNOWN_KEYS);

    let basedir: String = table.get("basedir")?;
    let bindfs: String = table
        .get::<Option<String>>("bindfs")?
        .unwrap_or_else(|| String::from("bindfs"));

    let actions_value: Value = table.get("actions")?;
    let actions = if actions_value.is_nil() {
        Vec::new()
    } else {
        let actions_table = actions_value
            .as_table()
            .ok_or_else(|| mlua::Error::runtime("'sandboxes.actions' must be a table"))?;
        parse_actions(actions_table, globals)?
    };

    Ok(Some(Sandboxes {
        basedir: PathBuf::from(basedir),
        actions,
        bindfs,
    }))
}

fn parse_actions(table: &Table, globals: &Table) -> LuaResult<Vec<Action>> {
    let mut actions = Vec::new();
    for v in table.sequence_values::<Table>() {
        let mut action = Action::from_lua(&v?)?;
        if let Some(varpath) = action.ifset().map(String::from) {
            match resolve_lua_var(globals, &varpath) {
                Some(val) => action.substitute_var(&varpath, &val),
                None => continue,
            }
        }
        actions.push(action);
    }
    Ok(actions)
}

/**
 * Resolve a dotted variable path (e.g. "pkgsrc.build_user") by
 * walking the Lua globals table.
 */
fn resolve_lua_var(globals: &Table, path: &str) -> Option<String> {
    let mut parts = path.split('.');
    let first = parts.next()?;
    let mut current: Value = globals.get(first).ok()?;
    for key in parts {
        match current {
            Value::Table(t) => {
                current = t.get(key).ok()?;
            }
            _ => return None,
        }
    }
    match current {
        Value::String(s) => Some(s.to_str().ok()?.to_string()),
        Value::Integer(n) => Some(n.to_string()),
        Value::Number(n) => Some(n.to_string()),
        _ => None,
    }
}

fn parse_environment(globals: &Table) -> LuaResult<Option<Environment>> {
    let environment: Value = globals.get("environment")?;
    if environment.is_nil() {
        return Ok(None);
    }

    let table = environment
        .as_table()
        .ok_or_else(|| mlua::Error::runtime("'environment' must be a table"))?;

    const KNOWN_KEYS: &[&str] = &["clear", "inherit", "set"];
    warn_unknown_keys(table, "environment", KNOWN_KEYS);

    let clear: bool = table.get::<Option<bool>>("clear")?.unwrap_or(true);

    let inherit: Vec<String> = match table.get::<Value>("inherit")? {
        Value::Nil => Vec::new(),
        Value::Table(t) => t
            .sequence_values::<String>()
            .filter_map(|r| r.ok())
            .collect(),
        _ => {
            return Err(mlua::Error::runtime(
                "'environment.inherit' must be a table",
            ));
        }
    };

    let set: HashMap<String, String> = match table.get::<Value>("set")? {
        Value::Nil => HashMap::new(),
        Value::Table(t) => {
            let mut map = HashMap::new();
            for pair in t.pairs::<String, String>() {
                let (k, v) = pair?;
                map.insert(k, v);
            }
            map
        }
        _ => return Err(mlua::Error::runtime("'environment.set' must be a table")),
    };

    Ok(Some(Environment {
        clear,
        inherit,
        set,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn load_config(lua_src: &str) -> Result<Config, String> {
        let dir = tempfile::tempdir().map_err(|e| e.to_string())?;
        let path = dir.path().join("config.lua");
        std::fs::write(&path, lua_src).map_err(|e| e.to_string())?;
        Config::load(Some(&path)).map_err(|e| e.to_string())
    }

    const MINIMAL: &str = r#"
        pkgsrc = {
            basedir = "/usr/pkgsrc",
            make = "/usr/bin/make",
        }
    "#;

    fn with_options(options: &str) -> String {
        format!("{MINIMAL}\noptions = {{ {options} }}")
    }

    fn with_dynamic(dynamic: &str) -> String {
        format!("{MINIMAL}\ndynamic = {{ {dynamic} }}")
    }

    #[test]
    fn options_valid_types() {
        let cfg = load_config(&with_options("build_threads = 4, scan_threads = 2"));
        assert!(cfg.is_ok());
        let cfg = cfg.ok();
        assert_eq!(cfg.as_ref().map(|c| c.build_threads()), Some(4));
        assert_eq!(cfg.as_ref().map(|c| c.scan_threads()), Some(2));
    }

    #[test]
    fn options_wrong_type_errors() {
        let cfg = load_config(&with_options("build_threads = \"eight\""));
        assert!(cfg.is_err(), "expected error, got: {:?}", cfg);
    }

    #[test]
    fn options_missing_is_default() {
        let cfg = load_config(MINIMAL);
        assert!(cfg.is_ok());
        let cfg = cfg.ok();
        assert_eq!(cfg.as_ref().map(|c| c.build_threads()), Some(1));
    }

    #[test]
    fn dynamic_jobs_wrong_type_errors() {
        let cfg = load_config(&with_dynamic("jobs = \"lots\""));
        assert!(cfg.is_err(), "expected error, got: {:?}", cfg);
    }

    #[test]
    fn pkgpaths_valid() {
        let lua = format!("{MINIMAL}\npkgsrc.pkgpaths = {{ \"devel/cmake\", \"lang/rust\" }}");
        let cfg = load_config(&lua);
        assert!(cfg.is_ok(), "expected ok, got: {:?}", cfg);
    }

    #[test]
    fn pkgpaths_invalid_errors() {
        let lua = format!("{MINIMAL}\npkgsrc.pkgpaths = {{ \"mail\" }}");
        let cfg = load_config(&lua);
        assert!(cfg.is_err(), "expected error, got: {:?}", cfg);
    }

    #[test]
    fn pkgpaths_wrong_type_errors() {
        let lua = format!("{MINIMAL}\npkgsrc.pkgpaths = {{ 42 }}");
        let cfg = load_config(&lua);
        assert!(cfg.is_err(), "expected error, got: {:?}", cfg);
    }
}