blackship 0.1.2

A FreeBSD jail manager with state machine control
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
//! Bridge for managing jail lifecycle and dependencies
//!
//! Handles:
//! - Building dependency graphs from configuration
//! - Starting jails in correct order (topological sort)
//! - Stopping jails in reverse order
//! - Managing ZFS datasets if enabled

use crate::bulkhead::{BulkheadManager, PortForward};
use crate::error::{Error, Result};
use crate::hooks::{HookContext, HookPhase, HookRunner};
use crate::jail::{
    jail_create, jail_getid, jail_remove, JailConfig, JailInstance, ParamValue,
};
use crate::jail::state::State as JailState;
use crate::manifest::{BlackshipConfig, DnsConfig};
use crate::network::{Bridge as NetworkBridge, IpAllocator, IpPool, VnetConfig, VnetSetup};
use crate::sys::OsVersion;
use crate::warden::WardenHandle;
use crate::zfs::ZfsManager;
use ipnet::IpNet;
use std::net::IpAddr;

use petgraph::algo::toposort;
use petgraph::graph::DiGraph;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use std::time::Instant;
use throttle_machines::token_bucket;

/// Bridge for managing jails
pub struct Bridge {
    /// Loaded configuration
    config: BlackshipConfig,

    /// Dependency graph (jail name -> node index)
    graph: DiGraph<String, ()>,

    /// ZFS manager (if enabled)
    zfs: Option<ZfsManager>,

    /// Bulkhead manager for PF firewall rules
    bulkhead: BulkheadManager,

    /// IP allocator for automatic IP assignment from network pools
    ip_allocator: IpAllocator,

    /// Map of jail name to allocated IP (for cleanup on stop)
    allocated_ips: HashMap<String, (String, IpAddr)>,

    /// Running jail instances
    instances: HashMap<String, JailInstance>,

    /// Verbose output mode
    verbose: bool,

    /// Rate limiter state for jail starts (tokens, last_refill)
    rate_limiter: Mutex<(f64, Instant)>,

    /// Rate limiter start time for consistent timing
    rate_limiter_epoch: Instant,

    /// Rate limiter capacity for jail starts
    jail_start_capacity: f64,

    /// Optional handle to notify the Warden of jail events
    warden_handle: Option<WardenHandle>,

    /// VNET setups for VNET jails (jail name -> VnetSetup)
    vnet_setups: HashMap<String, VnetSetup>,
}

impl Bridge {
    /// Create a new bridge from configuration
    pub fn new(config: BlackshipConfig) -> Result<Self> {
        // Detect OS version for feature compatibility checks
        let os_version = OsVersion::detect_kernel()?;

        // Check if VLAN filtering is being used and verify OS version
        if let Some(ref bridge_config) = config.config.bridge {
            if bridge_config.vlan_filtering && !os_version.supports_vlan_filtering() {
                return Err(Error::UnsupportedOsVersion {
                    feature: "VLAN filtering".to_string(),
                    minimum: "15.0".to_string(),
                    current: os_version.to_string(),
                });
            }

            // Setup bridge with VLAN filtering if configured
            if bridge_config.vlan_filtering {
                let bridge = NetworkBridge::create_or_open(&bridge_config.name)?;
                bridge.enable_vlan_filtering()?;

                // Add trunk interface if configured
                if let Some(ref trunk) = bridge_config.trunk {
                    // Disable hardware VLAN filter if requested (for Broadcom NICs)
                    if trunk.disable_hwfilter {
                        NetworkBridge::disable_hwfilter(&trunk.interface)?;
                    }

                    // Add trunk member with tagged VLANs
                    if !trunk.tagged.is_empty() {
                        bridge.add_trunk_member(&trunk.interface, &trunk.tagged)?;
                    }
                }
            }
        }

        let mut graph = DiGraph::new();
        let mut node_map = HashMap::new();

        // Add nodes for each jail
        for jail in &config.jails {
            let idx = graph.add_node(jail.name.clone());
            node_map.insert(jail.name.clone(), idx);
        }

        // Add edges for dependencies (dep -> jail)
        for jail in &config.jails {
            let to = node_map[&jail.name];
            for dep in &jail.depends_on {
                let from = node_map
                    .get(dep)
                    .ok_or_else(|| Error::UnknownDependency(dep.clone()))?;
                graph.add_edge(*from, to, ());
            }
        }

        // Initialize ZFS manager if enabled
        let zfs = if config.config.zfs_enabled {
            let pool = config.config.zpool.as_ref().ok_or(Error::ZfsNotEnabled)?;
            let zfs = ZfsManager::new(pool, &config.config.dataset);
            zfs.init()?;
            Some(zfs)
        } else {
            None
        };

        // Initialize bulkhead manager for PF firewall rules
        let bulkhead = BulkheadManager::new();

        // Initialize IP allocator from network configurations
        let mut ip_allocator = IpAllocator::new();
        for network in &config.networks {
            let subnet: IpNet = network.subnet.parse().map_err(|e| {
                Error::Network(format!(
                    "Invalid subnet '{}' for network '{}': {}",
                    network.subnet, network.name, e
                ))
            })?;

            let pool = if let Some(gateway) = network.gateway {
                IpPool::with_gateway(subnet, gateway)?
            } else {
                IpPool::new(subnet)?
            };

            ip_allocator.add_pool(network.name.clone(), pool);
        }

        let jail_start_capacity = config.config.rate_limit.jail_start_capacity;
        let now = Instant::now();
        Ok(Self {
            config,
            graph,
            zfs,
            bulkhead,
            ip_allocator,
            allocated_ips: HashMap::new(),
            instances: HashMap::new(),
            verbose: false,
            rate_limiter: Mutex::new((jail_start_capacity, now)), // Start with full capacity
            rate_limiter_epoch: now,
            jail_start_capacity,
            warden_handle: None,
            vnet_setups: HashMap::new(),
        })
    }

    /// Enable verbose output
    pub fn verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /// Set a Warden handle for jail event notifications
    pub fn set_warden_handle(&mut self, handle: WardenHandle) {
        self.warden_handle = Some(handle);
    }

    /// Resolve a jail identifier to (service_name, full_name)
    fn resolve_jail_names(&self, name: &str) -> Result<(String, String)> {
        self.config
            .resolve_jail_names(name)
            .ok_or_else(|| Error::JailNotFound(name.to_string()))
    }

    /// Get the start order (topological sort)
    pub fn start_order(&self) -> Result<Vec<&str>> {
        toposort(&self.graph, None)
            .map(|nodes| nodes.iter().map(|n| self.graph[*n].as_str()).collect())
            .map_err(|cycle| {
                // Get the node involved in the cycle
                let cycle_node = &self.graph[cycle.node_id()];
                Error::ConfigValidation(format!(
                    "Cyclic dependency detected involving jail '{}'",
                    cycle_node
                ))
            })
    }

    /// Get the stop order (reverse of start order)
    pub fn stop_order(&self) -> Result<Vec<&str>> {
        let mut order = self.start_order()?;
        order.reverse();
        Ok(order)
    }

    /// Start all jails (or a specific one with its dependencies)
    pub fn up(&mut self, jail: Option<&str>) -> Result<()> {
        // Collect to owned strings to avoid borrow conflict
        let jails_to_start: Vec<String> = if let Some(name) = jail {
            self.get_dependencies(name)?
                .into_iter()
                .map(String::from)
                .collect()
        } else {
            self.start_order()?.into_iter().map(String::from).collect()
        };

        for name in &jails_to_start {
            self.start_jail(name)?;
        }

        Ok(())
    }

    /// Stop all jails (or a specific one with its dependents)
    pub fn down(&mut self, jail: Option<&str>) -> Result<()> {
        // Collect to owned strings to avoid borrow conflict
        let jails_to_stop: Vec<String> = if let Some(name) = jail {
            self.get_dependents(name)?
                .into_iter()
                .map(String::from)
                .collect()
        } else {
            self.stop_order()?.into_iter().map(String::from).collect()
        };

        for name in &jails_to_stop {
            self.stop_jail(name)?;
        }

        Ok(())
    }

    /// Restart jails
    pub fn restart(&mut self, jail: Option<&str>) -> Result<()> {
        self.down(jail)?;
        self.up(jail)?;
        Ok(())
    }

    /// Dry run: show what 'up' would do without making changes
    pub fn up_dry_run(&self, jail: Option<&str>) -> Result<()> {
        println!("=== DRY RUN - No changes will be made ===\n");

        let jails_to_start: Vec<String> = if let Some(name) = jail {
            self.get_dependencies(name)?
                .into_iter()
                .map(String::from)
                .collect()
        } else {
            self.start_order()?.into_iter().map(String::from).collect()
        };

        println!("Would start {} jail(s):\n", jails_to_start.len());

        for name in &jails_to_start {
            let (service_name, full_name) = self.resolve_jail_names(name)?;
            let jail_def = self.config.get_jail(&service_name);
            if let Some(jail_def) = jail_def {
                let path = jail_def.effective_path(&self.config.config, &full_name);
                let ip = jail_def
                    .network
                    .as_ref()
                    .and_then(|n| n.ip)
                    .map(|ip| ip.to_string())
                    .unwrap_or_else(|| "none".to_string());

                println!("  [START] {}", full_name);
                println!("          Path: {}", path.display());
                println!("          IP: {}", ip);

                // Show if ZFS dataset would be created
                if self.zfs.is_some() && jail_def.path.is_none() {
                    println!("          ZFS: would create dataset");
                }

                // Show hooks that would run
                if !jail_def.hooks.is_empty() {
                    let pre_start: Vec<_> = jail_def
                        .hooks
                        .iter()
                        .filter(|h| h.phase == crate::hooks::HookPhase::PreStart)
                        .collect();
                    let post_start: Vec<_> = jail_def
                        .hooks
                        .iter()
                        .filter(|h| h.phase == crate::hooks::HookPhase::PostStart)
                        .collect();

                    if !pre_start.is_empty() {
                        println!("          Hooks: {} pre_start", pre_start.len());
                    }
                    if !post_start.is_empty() {
                        println!("          Hooks: {} post_start", post_start.len());
                    }
                }
                println!();
            }
        }

        Ok(())
    }

    /// Dry run: show what 'down' would do without making changes
    pub fn down_dry_run(&self, jail: Option<&str>) -> Result<()> {
        println!("=== DRY RUN - No changes will be made ===\n");

        let jails_to_stop: Vec<String> = if let Some(name) = jail {
            self.get_dependents(name)?
                .into_iter()
                .map(String::from)
                .collect()
        } else {
            self.stop_order()?.into_iter().map(String::from).collect()
        };

        println!("Would stop {} jail(s):\n", jails_to_stop.len());

        for name in &jails_to_stop {
            let (service_name, full_name) = self.resolve_jail_names(name)?;
            let is_running = jail_getid(&full_name).is_ok();
            let status = if is_running { "running" } else { "stopped" };

            println!("  [STOP] {} (currently {})", full_name, status);

            // Show hooks that would run
            if let Some(jail_def) = self.config.get_jail(&service_name)
                && !jail_def.hooks.is_empty() {
                    let pre_stop: Vec<_> = jail_def
                        .hooks
                        .iter()
                        .filter(|h| h.phase == crate::hooks::HookPhase::PreStop)
                        .collect();
                    let post_stop: Vec<_> = jail_def
                        .hooks
                        .iter()
                        .filter(|h| h.phase == crate::hooks::HookPhase::PostStop)
                        .collect();

                    if !pre_stop.is_empty() {
                        println!("         Hooks: {} pre_stop", pre_stop.len());
                    }
                    if !post_stop.is_empty() {
                        println!("         Hooks: {} post_stop", post_stop.len());
                    }
                }
        }

        println!();
        Ok(())
    }

    /// Print jail status
    pub fn ps(&self, json: bool) -> Result<()> {
        if json {
            let mut jails_data: Vec<serde_json::Value> = Vec::new();

            for jail_def in &self.config.jails {
                let full_name = self.config.jail_name(&jail_def.name);
                let (state, jid) = if let Some(instance) = self.instances.get(&full_name) {
                    let state = format!("{:?}", instance.state());
                    let jid = instance.jid;
                    (state, jid)
                } else {
                    match jail_getid(&full_name) {
                        Ok(jid) => ("Running".to_string(), Some(jid)),
                        Err(_) => ("Stopped".to_string(), None),
                    }
                };

                let ip = jail_def
                    .network
                    .as_ref()
                    .and_then(|n| n.ip)
                    .map(|ip| ip.to_string());

                jails_data.push(serde_json::json!({
                    "name": full_name,
                    "state": state,
                    "jid": jid,
                    "ip": ip,
                    "path": jail_def.effective_path(&self.config.config, &full_name).to_string_lossy()
                }));
            }

            println!("{}", serde_json::to_string_pretty(&jails_data).unwrap());
        } else {
            println!("{:<20} {:<10} {:<10}", "NAME", "STATE", "JID");
            println!("{}", "-".repeat(42));

            for jail_def in &self.config.jails {
                let full_name = self.config.jail_name(&jail_def.name);
                let (state, jid) = if let Some(instance) = self.instances.get(&full_name) {
                    let state = format!("{:?}", instance.state());
                    let jid = instance.jid.map(|j| j.to_string()).unwrap_or_default();
                    (state, jid)
                } else {
                    match jail_getid(&full_name) {
                        Ok(jid) => ("Running".to_string(), jid.to_string()),
                        Err(_) => ("Stopped".to_string(), String::new()),
                    }
                };

                println!("{:<20} {:<10} {:<10}", full_name, state, jid);
            }
        }

        Ok(())
    }

    /// Validate configuration
    pub fn check(&self) -> Result<()> {
        // Configuration was already validated on load
        println!("Configuration is valid.");

        // Check start order
        let order = self.start_order()?;
        println!("\nStart order:");
        for (i, name) in order.iter().enumerate() {
            let full_name = self.config.jail_name(name);
            println!("  {}. {}", i + 1, full_name);
        }

        // Check ZFS status
        if self.zfs.is_some() {
            println!("\nZFS: enabled");
        } else {
            println!("\nZFS: disabled");
        }

        // Check jail paths
        println!("\nJail paths:");
        for jail in &self.config.jails {
            let full_name = self.config.jail_name(&jail.name);
            let path = jail.effective_path(&self.config.config, &full_name);
            let exists = path.exists();
            let status = if exists { "exists" } else { "missing" };
            println!("  {}: {} ({})", full_name, path.display(), status);
        }

        Ok(())
    }

    /// Start a single jail with cleanup on failure
    fn start_jail(&mut self, name: &str) -> Result<()> {
        // Rate limiting to prevent thundering herd on `up --all`
        let capacity = self.jail_start_capacity;
        const REFILL_RATE: f64 = 1.0; // 1 jail/sec

        loop {
            let mut state = self.rate_limiter.lock().unwrap();
            let (tokens, last_refill) = *state;
            let now = Instant::now();
            let now_secs = now.duration_since(self.rate_limiter_epoch).as_secs_f64();
            let last_refill_secs = last_refill.duration_since(self.rate_limiter_epoch).as_secs_f64();

            let result = token_bucket::check(tokens, last_refill_secs, now_secs, capacity, REFILL_RATE);

            if result.allowed {
                // Update state and proceed
                *state = (result.new_tokens, now);
                break;
            } else {
                // Release lock before sleeping
                let retry_after = result.retry_after;
                drop(state);
                std::thread::sleep(std::time::Duration::from_secs_f64(retry_after));
            }
        }

        let (service_name, full_name) = self.resolve_jail_names(name)?;
        let jail_def = self
            .config
            .get_jail(&service_name)
            .ok_or_else(|| Error::JailNotFound(name.to_string()))?;

        // Check if already running
        if jail_getid(&full_name).is_ok() {
            return Err(Error::JailAlreadyRunning(full_name));
        }

        // Track resources for cleanup on failure
        let mut created_zfs_dataset = false;

        // Create ZFS dataset if needed (use full_name for system resources)
        let path = if let Some(zfs) = &self.zfs {
            if jail_def.path.is_none() {
                created_zfs_dataset = true;
                zfs.create_jail_dataset(&full_name)?
            } else {
                jail_def.effective_path(&self.config.config, &full_name)
            }
        } else {
            jail_def.effective_path(&self.config.config, &full_name)
        };

        // Check path exists - auto-provision from release if available
        if !path.exists() {
            // Check if we can auto-provision from a release
            if let Some(release) = &jail_def.release {
                let release_path = self.config.config.releases_dir.join(release);
                if release_path.exists() {
                    println!(
                        "Provisioning jail '{}' from release '{}'...",
                        full_name, release
                    );

                    // Create the jail directory
                    if let Err(e) = std::fs::create_dir_all(&path) {
                        // Cleanup ZFS dataset if we created it
                        if created_zfs_dataset
                            && let Some(zfs) = &self.zfs {
                                let _ = zfs.destroy_jail_dataset(&full_name);
                            }
                        return Err(Error::JailOperation(format!(
                            "Failed to create jail directory: {}",
                            e
                        )));
                    }

                    // Copy release to jail path using cp -a for full recursive copy
                    let status = std::process::Command::new("cp")
                        .arg("-a")
                        .arg(format!("{}/.", release_path.display()))
                        .arg(&path)
                        .status();

                    match status {
                        Ok(s) if s.success() => {
                            println!("Jail '{}' provisioned from release '{}'", full_name, release);
                        }
                        Ok(s) => {
                            // Cleanup on failure
                            let _ = std::fs::remove_dir_all(&path);
                            if created_zfs_dataset
                                && let Some(zfs) = &self.zfs {
                                    let _ = zfs.destroy_jail_dataset(&full_name);
                                }
                            return Err(Error::JailOperation(format!(
                                "Failed to copy release: cp exited with status {}",
                                s
                            )));
                        }
                        Err(e) => {
                            // Cleanup on failure
                            let _ = std::fs::remove_dir_all(&path);
                            if created_zfs_dataset
                                && let Some(zfs) = &self.zfs {
                                    let _ = zfs.destroy_jail_dataset(&full_name);
                                }
                            return Err(Error::JailOperation(format!(
                                "Failed to execute cp command: {}",
                                e
                            )));
                        }
                    }
                } else {
                    // Release not found
                    if created_zfs_dataset
                        && let Some(zfs) = &self.zfs {
                            let _ = zfs.destroy_jail_dataset(&full_name);
                        }
                    return Err(Error::JailOperation(format!(
                        "Release '{}' not found at {}. Run 'blackship bootstrap {}' first.",
                        release,
                        release_path.display(),
                        release
                    )));
                }
            } else {
                // No release specified, return original error
                // Cleanup ZFS dataset if we created it
                if created_zfs_dataset
                    && let Some(zfs) = &self.zfs {
                        let _ = zfs.destroy_jail_dataset(&full_name);
                    }
                return Err(Error::JailPathNotFound(path));
            }
        }

        // Configure DNS before starting the jail
        if let Some(network) = &jail_def.network
            && let Err(e) = self.configure_dns(&path, &network.dns) {
                // Cleanup on DNS config failure
                if created_zfs_dataset
                    && let Some(zfs) = &self.zfs {
                        let _ = zfs.destroy_jail_dataset(&full_name);
                    }
                return Err(e);
            }

        // Determine IP address for this jail
        // Priority: static IP > auto-allocate from network pool > none
        let mut allocated_ip: Option<(String, IpAddr)> = None;
        let effective_ip: Option<IpAddr> = if let Some(network) = &jail_def.network {
            if let Some(static_ip) = network.ip {
                // Static IP configured - reserve it in pools if attached to a network
                for net_name in &network.networks {
                    if let Some(pool) = self.ip_allocator.get_pool_mut(net_name) {
                        // Try to reserve the static IP in the pool (ignore errors if not in subnet)
                        let _ = pool.allocate_specific(static_ip);
                    }
                }
                Some(static_ip)
            } else if let Some(first_network) = network.networks.first() {
                // No static IP but attached to a network - auto-allocate
                match self.ip_allocator.allocate(first_network) {
                    Ok(ip) => {
                        allocated_ip = Some((first_network.clone(), ip));
                        if self.verbose {
                            println!("  Auto-allocated IP {} from network '{}'", ip, first_network);
                        }
                        Some(ip)
                    }
                    Err(e) => {
                        // Cleanup on allocation failure
                        if created_zfs_dataset
                            && let Some(zfs) = &self.zfs {
                                let _ = zfs.destroy_jail_dataset(&full_name);
                            }
                        return Err(e);
                    }
                }
            } else {
                None
            }
        } else {
            None
        };

        // Setup hook runner and context
        let hook_runner = HookRunner::new(jail_def.hooks.clone()).verbose(self.verbose);
        let mut hook_context = HookContext::new(&full_name, &path);

        // Add IP to context if available
        if let Some(ip) = effective_ip {
            hook_context = hook_context.with_ip(ip.to_string());
        }

        // Execute pre_start hooks
        if let Err(e) = hook_runner.execute_phase(HookPhase::PreStart, &hook_context) {
            // Cleanup on pre_start hook failure
            if let Some((network_name, ip)) = &allocated_ip {
                self.ip_allocator.release(network_name, ip);
            }
            if created_zfs_dataset
                && let Some(zfs) = &self.zfs {
                    let _ = zfs.destroy_jail_dataset(&full_name);
                }
            return Err(e);
        }

        // Check if this is a VNET jail
        let is_vnet = jail_def.network.as_ref().is_some_and(|n| n.vnet);

        // Create VNET setup for VNET jails before creating the jail
        let mut vnet_setup: Option<VnetSetup> = None;
        if is_vnet
            && let Some(network) = &jail_def.network {
                // Validate VNET configuration
                let bridge_name = network.bridge.as_ref().ok_or_else(|| {
                    Error::Network(format!(
                        "VNET jail '{}' requires a bridge configuration",
                        full_name
                    ))
                })?;

                // Build IP configuration string for VnetConfig
                let ip_config = network
                    .ip_cidr
                    .as_ref()
                    .cloned()
                    .or_else(|| network.ip.map(|ip| format!("{}/24", ip)))
                    .or_else(|| effective_ip.map(|ip| format!("{}/24", ip)))
                    .unwrap_or_else(|| "0.0.0.0/0".to_string());

                // Get gateway (required for VnetConfig)
                let gateway = network.gateway.unwrap_or_else(|| {
                    // Default gateway - first IP in subnet if not specified
                    "10.0.0.1".parse().unwrap()
                });

                // Build VnetConfig
                let mut vnet_config = VnetConfig::new(bridge_name.clone(), ip_config, gateway);

                // Set static MAC address if configured
                if let Some(ref mac) = network.mac_address {
                    vnet_config = vnet_config.with_mac_address(mac.clone());
                }

                // Set VLAN ID if configured (FreeBSD 15.0+)
                if let Some(vlan_id) = network.vlan_id {
                    vnet_config = vnet_config.with_vlan_id(vlan_id);
                }

                // Create VnetSetup - this handles epair creation, MAC setting, and bridge addition
                let setup = match VnetSetup::create(&full_name, vnet_config) {
                    Ok(s) => s,
                    Err(e) => {
                        // Cleanup on VnetSetup creation failure
                        if let Some((network_name, ip)) = &allocated_ip {
                            self.ip_allocator.release(network_name, ip);
                        }
                        if created_zfs_dataset
                            && let Some(zfs) = &self.zfs {
                                let _ = zfs.destroy_jail_dataset(&full_name);
                            }
                        return Err(e);
                    }
                };

                if self.verbose {
                    println!(
                        "  Created epair {} <-> {} for VNET jail",
                        setup.epair.host_side(),
                        setup.epair.jail_side()
                    );
                    println!(
                        "  Added {} to bridge {}",
                        setup.epair.host_side(),
                        bridge_name
                    );
                }

                vnet_setup = Some(setup);
            }

        // Build jail parameters (use full_name for FreeBSD jail name)
        let mut params = HashMap::new();
        params.insert("name".to_string(), ParamValue::String(full_name.clone()));

        if let Some(hostname) = &jail_def.hostname {
            params.insert(
                "host.hostname".to_string(),
                ParamValue::String(hostname.clone()),
            );
        }

        // For VNET jails, enable vnet and don't set IP (configured inside jail)
        // For non-VNET jails, use traditional IP assignment
        if is_vnet {
            // Enable VNET for this jail
            params.insert("vnet".to_string(), ParamValue::String("new".to_string()));
        } else if let Some(ip) = effective_ip {
            // Traditional jail: assign IP directly
            match ip {
                IpAddr::V4(addr) => {
                    params.insert("ip4.addr".to_string(), ParamValue::Ipv4(vec![addr]));
                }
                IpAddr::V6(addr) => {
                    params.insert("ip6.addr".to_string(), ParamValue::Ipv6(vec![addr]));
                }
            }
        }

        // Add custom parameters
        for (key, value) in &jail_def.params {
            let param_value = ParamValue::try_from(value)?;
            params.insert(key.clone(), param_value);
        }

        // Create the jail
        println!("Starting jail '{}'...", full_name);
        let jid = match jail_create(&path, params) {
            Ok(jid) => jid,
            Err(e) => {
                // Cleanup on jail creation failure
                eprintln!("Failed to create jail '{}': {}", full_name, e);
                // Cleanup VnetSetup if created
                if let Some(setup) = vnet_setup {
                    let _ = setup.cleanup();
                }
                // Release allocated IP
                if let Some((network_name, ip)) = &allocated_ip {
                    self.ip_allocator.release(network_name, ip);
                }
                if created_zfs_dataset {
                    eprintln!("Cleaning up ZFS dataset...");
                    if let Some(zfs) = &self.zfs {
                        let _ = zfs.destroy_jail_dataset(&full_name);
                    }
                }
                // Track the failed instance
                let jail_config = JailConfig::new(&full_name, &path);
                let mut instance = JailInstance::new(jail_config);
                instance.start().ok(); // Transition to Starting
                instance.fail().ok();  // Transition to Failed
                self.instances.insert(full_name.clone(), instance);
                // Notify Warden of failure
                if let Some(handle) = &self.warden_handle {
                    let _ = handle.notify_failure_blocking(&full_name);
                }
                return Err(e);
            }
        };
        println!("Jail '{}' started with JID {}", full_name, jid);


        // For VNET jails: attach the VnetSetup to the jail (moves interface and configures networking)
        if let Some(setup) = vnet_setup {
            // Use VnetSetup::attach_to_jail which handles both moving interface and configuring
            if let Err(e) = setup.attach_to_jail(jid) {
                eprintln!(
                    "Warning: Failed to attach VNET to jail '{}': {}",
                    full_name, e
                );
                eprintln!("VNET networking may not work correctly.");
            } else if self.verbose {
                println!(
                    "  Moved {} into jail {} (JID {})",
                    setup.jail_interface(),
                    full_name,
                    jid
                );
                println!(
                    "  Configured {} with {} in jail",
                    setup.jail_interface(),
                    setup.config.ip
                );
                println!("  Set default gateway to {}", setup.config.gateway);
            }

            // Store the VnetSetup for cleanup on stop
            self.vnet_setups.insert(full_name.clone(), setup);
        }

        // Update context with JID for post_start hooks
        let hook_context = hook_context.with_jid(jid);

        // Execute post_start hooks (failure here doesn't cleanup the jail)
        if let Err(e) = hook_runner.execute_phase(HookPhase::PostStart, &hook_context) {
            eprintln!("Warning: post_start hook failed for jail '{}': {}", full_name, e);
            eprintln!("Jail is running but may not be fully configured.");
        }

        // Track the instance with full configuration
        let mut jail_config = JailConfig::new(&full_name, &path);
        if let Some(hostname) = &jail_def.hostname {
            jail_config = jail_config.hostname(hostname);
        }
        if let Some(ip) = effective_ip {
            jail_config = jail_config.ip(ip);
        }
        let mut instance = JailInstance::new(jail_config);
        instance.jid = Some(jid);
        instance.start().ok();
        instance.started().ok();
        self.instances.insert(full_name.clone(), instance);

        // Track allocated IP for cleanup on stop
        if let Some(alloc) = allocated_ip {
            self.allocated_ips.insert(full_name.clone(), alloc);
        }

        // Notify Warden that jail started successfully
        if let Some(handle) = &self.warden_handle
            && let Err(e) = handle.notify_started_blocking(&full_name) {
                eprintln!("Warning: Failed to notify Warden of jail start: {}", e);
            }

        Ok(())
    }

    /// Force cleanup of a failed jail
    ///
    /// Removes any leftover resources from a failed jail start:
    /// - Kills any processes
    /// - Removes jail if partially created
    /// - Destroys ZFS dataset if created by blackship
    pub fn cleanup(&mut self, name: &str, force: bool) -> Result<()> {
        let (service_name, full_name) = self.resolve_jail_names(name)?;
        println!("Cleaning up jail '{}'...", full_name);

        // Try to get jail definition
        let jail_def = self.config.get_jail(&service_name);

        // Try to remove jail if it exists (even partially)
        if let Ok(jid) = jail_getid(&full_name) {
            println!("  Removing jail (JID {})...", jid);
            if let Err(e) = jail_remove(jid) {
                if force {
                    eprintln!("  Warning: Failed to remove jail: {}", e);
                } else {
                    return Err(e);
                }
            }
        }

        // Clean up ZFS dataset if we manage it
        if let Some(zfs) = &self.zfs
            && let Some(jail_def) = jail_def {
                // Only destroy if path is managed by blackship (not custom path)
                if jail_def.path.is_none() {
                    println!("  Destroying ZFS dataset...");
                    if let Err(e) = zfs.destroy_jail_dataset(&full_name) {
                        if force {
                            eprintln!("  Warning: Failed to destroy dataset: {}", e);
                        } else {
                            return Err(e);
                        }
                    }
                }
        }

        // Remove from instances
        self.instances.remove(&full_name);

        // Cleanup VNET epair interface if present
        if let Some(vnet_setup) = self.vnet_setups.remove(&full_name) {
            println!("  Cleaning up VNET setup...");
            if let Err(e) = vnet_setup.cleanup() {
                if force {
                    eprintln!("  Warning: Failed to cleanup VNET setup: {}", e);
                } else {
                    return Err(e);
                }
            }
        }

        // Release allocated IP back to the pool
        if let Some((network_name, ip)) = self.allocated_ips.remove(&full_name) {
            self.ip_allocator.release(&network_name, &ip);
            println!("  Released IP {} back to network '{}'", ip, network_name);
        }

        println!("Cleanup complete for jail '{}'", full_name);
        Ok(())
    }

    /// Stop a single jail
    fn stop_jail(&mut self, name: &str) -> Result<()> {
        let (service_name, full_name) = self.resolve_jail_names(name)?;

        // Get JID
        let jid = match jail_getid(&full_name) {
            Ok(jid) => jid,
            Err(_) => {
                return Err(Error::JailNotRunning(full_name));
            }
        };

        // Get jail definition for hooks
        let jail_def = self.config.get_jail(&service_name);

        // Setup hooks if jail has hook configuration
        if let Some(jail_def) = jail_def {
            let path = jail_def.effective_path(&self.config.config, &full_name);
            let hook_runner = HookRunner::new(jail_def.hooks.clone()).verbose(self.verbose);
            let mut hook_context = HookContext::new(&full_name, &path).with_jid(jid);

            // Add IP to context if available
            if let Some(network) = &jail_def.network
                && let Some(ip) = &network.ip {
                    hook_context = hook_context.with_ip(ip.to_string());
                }

            // Execute pre_stop hooks (inside jail, while still running)
            hook_runner.execute_phase(HookPhase::PreStop, &hook_context)?;

            // Remove the jail
            println!("Stopping jail '{}'...", full_name);
            jail_remove(jid)?;
            println!("Jail '{}' stopped", full_name);

            // Execute post_stop hooks (on host, after jail stopped)
            // Note: JID is no longer valid, but path and name are
            let hook_context = HookContext::new(&full_name, &path);
            hook_runner.execute_phase(HookPhase::PostStop, &hook_context)?;
        } else {
            // No jail definition found, just stop directly
            println!("Stopping jail '{}'...", full_name);
            jail_remove(jid)?;
            println!("Jail '{}' stopped", full_name);
        }

        // Update instance state
        if let Some(instance) = self.instances.get_mut(&full_name) {
            instance.stop().ok();
            instance.stopped().ok();
            instance.jid = None;
        }

        // Cleanup VNET setup if present
        if let Some(vnet_setup) = self.vnet_setups.remove(&full_name) {
            if let Err(e) = vnet_setup.cleanup() {
                eprintln!("Warning: Failed to cleanup VNET setup for jail '{}': {}", full_name, e);
            } else if self.verbose {
                println!("  Cleaned up VNET for bridge {}", vnet_setup.bridge_name);
            }
        }

        // Release allocated IP back to the pool
        if let Some((network_name, ip)) = self.allocated_ips.remove(&full_name) {
            self.ip_allocator.release(&network_name, &ip);
            if self.verbose {
                println!("  Released IP {} back to network '{}'", ip, network_name);
            }
        }

        // Notify Warden that jail stopped
        if let Some(handle) = &self.warden_handle
            && let Err(e) = handle.notify_stopped_blocking(&full_name) {
                eprintln!("Warning: Failed to notify Warden of jail stop: {}", e);
            }

        Ok(())
    }

    /// Restart a jail (stop then start)
    ///
    /// Used by the Warden for automatic restart on failure
    pub fn restart_jail(&mut self, name: &str) -> Result<()> {
        let (service_name, full_name) = self.resolve_jail_names(name)?;
        println!("Restarting jail '{}'...", full_name);

        // If the jail is in Failed state, recover it first
        if let Some(instance) = self.instances.get_mut(&full_name)
            && instance.state() == JailState::Failed {
                instance.recover().ok(); // Transition from Failed to Stopped
            }

        // Stop if running
        if jail_getid(&full_name).is_ok() {
            self.stop_jail(&service_name)?;
        }

        // Start the jail
        self.start_jail(&service_name)?;

        println!("Jail '{}' restarted successfully", full_name);
        Ok(())
    }

    /// Get all dependencies of a jail (including the jail itself)
    fn get_dependencies(&self, name: &str) -> Result<Vec<&str>> {
        let (service_name, _full_name) = self.resolve_jail_names(name)?;
        let order = self.start_order()?;
        let idx = order
            .iter()
            .position(|n| *n == service_name)
            .ok_or_else(|| Error::JailNotFound(name.to_string()))?;

        // Return all jails up to and including this one
        Ok(order[..=idx].to_vec())
    }

    /// Get all dependents of a jail (including the jail itself)
    fn get_dependents(&self, name: &str) -> Result<Vec<&str>> {
        let (service_name, _full_name) = self.resolve_jail_names(name)?;
        let order = self.stop_order()?;
        let idx = order
            .iter()
            .position(|n| *n == service_name)
            .ok_or_else(|| Error::JailNotFound(name.to_string()))?;

        // Return all jails from the start up to and including this one
        Ok(order[..=idx].to_vec())
    }

    /// Configure DNS in a jail
    fn configure_dns(&self, jail_path: &Path, dns_config: &DnsConfig) -> Result<()> {
        let resolv_path = jail_path.join("etc/resolv.conf");

        if dns_config.is_inherit() {
            // Copy from host
            std::fs::copy("/etc/resolv.conf", &resolv_path)
                .map_err(|e| Error::JailOperation(format!("Failed to copy resolv.conf: {}", e)))?;
        } else if let Some(content) = dns_config.to_resolv_conf() {
            // Write custom resolv.conf
            std::fs::write(&resolv_path, content)
                .map_err(|e| Error::JailOperation(format!("Failed to write resolv.conf: {}", e)))?;
        }

        Ok(())
    }

    /// Initialize the PF firewall anchor for port forwarding
    ///
    /// This should be called once at startup to ensure PF is properly configured.
    pub fn init_bulkhead(&self) -> Result<()> {
        BulkheadManager::init()
    }

    /// Expose a port from a jail to the host
    ///
    /// Creates a PF RDR rule to forward traffic from the external port to the jail.
    pub fn expose_port(
        &mut self,
        jail_name: &str,
        external_port: u16,
        internal_port: Option<u16>,
        protocol: &str,
        bind_ip: Option<IpAddr>,
    ) -> Result<PortForward> {
        // Verify jail exists and get its IP
        let (service_name, full_name) = self.resolve_jail_names(jail_name)?;
        let jail_def = self
            .config
            .get_jail(&service_name)
            .ok_or_else(|| Error::JailNotFound(jail_name.to_string()))?;

        let jail_ip = jail_def
            .network
            .as_ref()
            .and_then(|n| n.ip)
            .ok_or_else(|| {
                Error::Network(format!(
                    "Jail '{}' has no IP address configured",
                    full_name
                ))
            })?;

        // Create port forward rule
        let internal = internal_port.unwrap_or(external_port);
        let mut forward = PortForward::new(external_port, internal, protocol, jail_ip, &full_name);

        if let Some(ip) = bind_ip {
            forward = forward.with_bind_ip(ip);
        }

        // Add to bulkhead manager and apply
        self.bulkhead.add_forward(forward.clone())?;

        if self.verbose {
            println!(
                "Exposed port {}:{}/{} -> {}:{}",
                bind_ip.map(|ip| ip.to_string()).unwrap_or_else(|| "*".to_string()),
                external_port,
                protocol,
                jail_ip,
                internal
            );
        }

        Ok(forward)
    }

    /// Remove all port forwards for a jail
    pub fn remove_port_forwards(&mut self, jail_name: &str) -> Result<()> {
        let (_service_name, full_name) = self.resolve_jail_names(jail_name)?;
        self.bulkhead.remove_jail_forwards(&full_name)?;

        if self.verbose {
            println!("Removed port forwards for jail '{}'", full_name);
        }

        Ok(())
    }

    /// List all active port forwards
    pub fn list_port_forwards(&self) -> &[PortForward] {
        self.bulkhead.list_forwards()
    }

    /// Get port forwards for a specific jail
    pub fn get_jail_port_forwards(&self, jail_name: &str) -> Vec<&PortForward> {
        if let Some((_service_name, full_name)) = self.config.resolve_jail_names(jail_name) {
            self.bulkhead.get_jail_forwards(&full_name)
        } else {
            Vec::new()
        }
    }
}

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

    fn test_config() -> BlackshipConfig {
        toml::from_str(
            r#"
[config]
data_dir = "/var/blackship"

[[jails]]
name = "database"
path = "/jails/database"

[[jails]]
name = "backend"
path = "/jails/backend"
depends_on = ["database"]

[[jails]]
name = "frontend"
path = "/jails/frontend"
depends_on = ["backend"]
"#,
        )
        .unwrap()
    }

    #[test]
    fn test_start_order() {
        let config = test_config();
        let bridge = Bridge::new(config).unwrap();
        let order = bridge.start_order().unwrap();
        assert_eq!(order, vec!["database", "backend", "frontend"]);
    }

    #[test]
    fn test_stop_order() {
        let config = test_config();
        let bridge = Bridge::new(config).unwrap();
        let order = bridge.stop_order().unwrap();
        assert_eq!(order, vec!["frontend", "backend", "database"]);
    }
}