yconn 1.12.0

SSH connection manager for teams and DevOps environments
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
// Handler for `yconn ssh-config generate` — write SSH Host blocks to
// ~/.ssh/yconn-connections and update ~/.ssh/config with an Include line.

use std::collections::HashMap;
use std::fs;
use std::io::{self, BufRead, Write};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};

use crate::config::{Connection, LoadedConfig};
use crate::display::Renderer;

use super::user::write_user_entry;

// ─── Translation helpers ──────────────────────────────────────────────────────

/// Translate a yconn connection name to a valid SSH `Host` pattern.
///
/// - Glob names (`web-*`, `srv-?`) are valid SSH `Host` patterns as-is.
/// - Range names (`server[1..10]`) have the `[N..M]` suffix replaced with `*`
///   so SSH sees `server*`.
/// - Literal names are returned unchanged.
fn translate_name_for_ssh(name: &str) -> String {
    if let Some(bracket) = name.rfind('[') {
        let suffix = &name[bracket..];
        if suffix.ends_with(']') && suffix.contains("..") {
            return format!("{}*", &name[..bracket]);
        }
    }
    name.to_string()
}

/// Translate a yconn `host` field value to an SSH `HostName` value.
///
/// `${name}` is replaced with `%h` — SSH's token that expands to the hostname
/// supplied on the command line. This allows a wildcard `Host` block to derive
/// its real target from the input (e.g. `HostName %h.corp.com`).
fn translate_host_for_ssh(host: &str) -> String {
    host.replace("${name}", "%h")
}

// ─── Rendering ────────────────────────────────────────────────────────────────

/// Build the full SSH config text for `connections`.
///
/// Every connection produces a `Host` block. Pattern names are translated:
/// - Glob (`*`, `?`) — used directly as the SSH `Host` pattern.
/// - Range (`[N..M]`) — the range suffix is replaced with `*`.
///
/// `${name}` in the `host` field is replaced with `%h` so SSH expands it to
/// the matched hostname at connection time.
///
/// When `skip_user` is `true`, the `User` line is omitted from all blocks.
///
/// The output contains no trailing newline after the last block.
pub fn render_ssh_config(connections: &[Connection], skip_user: bool) -> String {
    let mut out = String::new();

    for conn in connections {
        let ssh_host = translate_name_for_ssh(&conn.name);
        let ssh_hostname = translate_host_for_ssh(&conn.host);

        // Determine whether the user field contains an unresolved template token.
        // This is evaluated once and used both for the pre-Host comment and for
        // suppressing the User directive inside the block.
        let has_unresolved_user = !skip_user && conn.user.contains("${");

        // All comment lines appear contiguously before the Host line.
        out.push_str(&format!("# description: {}\n", conn.description));
        out.push_str(&format!("# auth: {}\n", conn.auth.type_label()));
        if let Some(link) = &conn.link {
            out.push_str(&format!("# link: {link}\n"));
        }
        // If the user field still contains an unresolved template token,
        // emit a comment here (before Host) instead of an invalid SSH User
        // directive inside the block.
        if has_unresolved_user {
            out.push_str(&format!("# user: {} (unresolved)\n", conn.user));
        }

        out.push_str(&format!("Host {ssh_host}\n"));
        out.push_str(&format!("    HostName {ssh_hostname}\n"));
        if !skip_user && !has_unresolved_user {
            out.push_str(&format!("    User {}\n", conn.user));
        }
        if conn.port != 22 {
            out.push_str(&format!("    Port {}\n", conn.port));
        }
        if let Some(key) = conn.auth.key() {
            out.push_str(&format!("    IdentityFile {key}\n"));
            if matches!(conn.auth, crate::config::Auth::Identity { .. }) {
                out.push_str("    IdentitiesOnly yes\n");
            }
        }
        out.push('\n');
    }

    // Remove the trailing newline after the last block so callers can control
    // the final newline themselves.
    if out.ends_with('\n') {
        out.pop();
    }

    out
}

// ─── File helpers ─────────────────────────────────────────────────────────────

const INCLUDE_LINE: &str = "Include ~/.ssh/yconn-connections";
const OUTPUT_FILENAME: &str = "yconn-connections";

/// Return the path to `~/.ssh/yconn-connections`.
fn output_path(home: &Path) -> PathBuf {
    home.join(".ssh").join(OUTPUT_FILENAME)
}

/// Ensure `~/.ssh/` exists with 0o700 permissions.
fn ensure_ssh_dir(home: &Path) -> Result<()> {
    let ssh_dir = home.join(".ssh");
    if !ssh_dir.exists() {
        fs::create_dir_all(&ssh_dir)
            .with_context(|| format!("failed to create {}", ssh_dir.display()))?;
        fs::set_permissions(&ssh_dir, fs::Permissions::from_mode(0o700))
            .with_context(|| format!("failed to set permissions on {}", ssh_dir.display()))?;
    }
    Ok(())
}

/// Write `content` to `path` with 0o600 permissions.
fn write_secure(path: &Path, content: &str) -> Result<()> {
    fs::write(path, content).with_context(|| format!("failed to write {}", path.display()))?;
    fs::set_permissions(path, fs::Permissions::from_mode(0o600))
        .with_context(|| format!("failed to set permissions on {}", path.display()))?;
    Ok(())
}

/// Ensure `~/.ssh/config` contains `Include ~/.ssh/yconn-connections` as its
/// first non-empty line. Creates the file if absent.
fn inject_include(home: &Path) -> Result<()> {
    let config_path = home.join(".ssh").join("config");

    if config_path.exists() {
        let existing = fs::read_to_string(&config_path)
            .with_context(|| format!("failed to read {}", config_path.display()))?;
        if existing.lines().any(|l| l.trim() == INCLUDE_LINE) {
            return Ok(()); // Already present — idempotent.
        }
        let updated = format!("{INCLUDE_LINE}\n\n{existing}");
        write_secure(&config_path, &updated)?;
    } else {
        write_secure(&config_path, &format!("{INCLUDE_LINE}\n"))?;
    }
    Ok(())
}

// ─── Host block upsert ────────────────────────────────────────────────────────

/// A single Host block from a `yconn-connections` file: the SSH Host pattern
/// and the full text of the block (including any preceding comment lines and
/// the trailing newline).
#[derive(Debug, PartialEq)]
struct HostBlock {
    /// The SSH Host pattern as it appears on the `Host <pattern>` line.
    ssh_host: String,
    /// Full block text, including preamble comments and a trailing blank line.
    text: String,
}

/// Parse the contents of `~/.ssh/yconn-connections` into an ordered list of
/// `HostBlock` values.
///
/// The format produced by `render_ssh_config` is:
///
/// ```text
/// # description: …
/// # auth: …
/// Host <name>
///     HostName …
//////
/// ```
///
/// A block boundary is a blank line. Lines before the first `Host` line in a
/// block are treated as that block's preamble (comment lines). The `Host`
/// pattern is extracted from lines matching `^Host <single-token>$`.
///
/// Wildcard Host patterns (e.g. `Host web-*`) are matched exactly — they are
/// not expanded.
fn parse_host_blocks(content: &str) -> Vec<HostBlock> {
    let mut blocks: Vec<HostBlock> = Vec::new();

    // Collect lines, grouping them into blocks separated by blank lines.
    // We accumulate a "pending" chunk of lines; when we hit a blank line we
    // finalise the chunk into a block if it contains a `Host` line.
    let mut pending: Vec<&str> = Vec::new();

    for line in content.lines() {
        if line.is_empty() {
            // Blank line: finalise any pending chunk.
            if !pending.is_empty() {
                if let Some(block) = finalise_block(&pending) {
                    blocks.push(block);
                }
                pending.clear();
            }
        } else {
            pending.push(line);
        }
    }

    // Handle a trailing block with no terminating blank line.
    if !pending.is_empty() {
        if let Some(block) = finalise_block(&pending) {
            blocks.push(block);
        }
    }

    blocks
}

/// Build a `HostBlock` from a non-empty slice of non-blank lines.
///
/// Scans for the first line matching `^Host <token>$` and uses the token as
/// the SSH host pattern. If no such line is found, returns `None` (the chunk
/// is kept as-is but cannot participate in keyed merge).
fn finalise_block(lines: &[&str]) -> Option<HostBlock> {
    let ssh_host = lines.iter().find_map(|l| {
        let rest = l.strip_prefix("Host ")?;
        // Ensure it is exactly one token (no embedded spaces).
        if !rest.is_empty() && !rest.contains(' ') {
            Some(rest.to_string())
        } else {
            None
        }
    })?;

    // Reconstruct block text: all lines joined with '\n', plus a trailing '\n'
    // so blocks end at a newline, followed by a blank line separator.
    let text = format!("{}\n\n", lines.join("\n"));
    Some(HostBlock { ssh_host, text })
}

/// Merge the newly rendered blocks into the existing set of blocks, then
/// return the full file content.
///
/// Merge strategy:
/// - Walk existing blocks in order. If a block's `ssh_host` matches one from
///   `new_blocks`, replace its text with the new block's text; remove the new
///   block from the pending set so it is not appended again.
/// - Append any remaining new blocks (those not present in the existing file)
///   after the preserved/updated existing blocks.
///
/// This preserves "foreign" blocks (those not in the current yconn config)
/// unchanged while updating only matching blocks in place.
fn merge_host_blocks(existing: Vec<HostBlock>, new_blocks: Vec<HostBlock>) -> String {
    use std::collections::HashMap;

    // Build a map from ssh_host → block text for fast lookup.
    let mut new_map: HashMap<String, String> = new_blocks
        .iter()
        .map(|b| (b.ssh_host.clone(), b.text.clone()))
        .collect();

    // Track which new blocks were consumed (matched an existing entry).
    let mut merged = String::new();

    for existing_block in &existing {
        if let Some(new_text) = new_map.remove(&existing_block.ssh_host) {
            // Replace the existing block with the new text.
            merged.push_str(&new_text);
        } else {
            // Preserve the foreign block unchanged.
            merged.push_str(&existing_block.text);
        }
    }

    // Append new blocks that were not present in the existing file, in the
    // same order they appear in new_blocks.
    for new_block in &new_blocks {
        if new_map.contains_key(&new_block.ssh_host) {
            merged.push_str(&new_block.text);
        }
    }

    // The final content should end with exactly one newline (each block ends
    // with "\n\n", so the last block has a trailing blank line; strip it so
    // write_secure appends a single "\n" consistently).
    if merged.ends_with("\n\n") {
        merged.truncate(merged.len() - 1);
    }

    merged
}

// ─── Warning helpers ──────────────────────────────────────────────────────────

/// Extract the first unresolved template key from a user field value.
///
/// When `expand_user_field` cannot resolve a `${key}` token it leaves the
/// token unchanged in the returned string.  This helper finds the first such
/// token and returns the key name so the caller can compose a fix command.
///
/// Returns `None` if no `${...}` token is present.
pub(crate) fn extract_unresolved_key(value: &str) -> Option<&str> {
    let start = value.find("${")?;
    let rest = &value[start + 2..];
    let end = rest.find('}')?;
    Some(&rest[..end])
}

/// Remove the `Include ~/.ssh/yconn-connections` line from `~/.ssh/config`.
///
/// Preserves all other content unchanged. Returns `true` if the line was
/// found and removed, `false` if it was already absent.
pub fn remove_include_line(home: &Path) -> Result<bool> {
    let config_path = home.join(".ssh").join("config");
    if !config_path.exists() {
        return Ok(false);
    }
    let existing = fs::read_to_string(&config_path)
        .with_context(|| format!("failed to read {}", config_path.display()))?;
    if !existing.lines().any(|l| l.trim() == INCLUDE_LINE) {
        return Ok(false);
    }
    // Remove the Include line, then strip any leading blank lines that were
    // left behind (inject_include inserts "\n\n" after the Include line).
    let updated = existing
        .lines()
        .filter(|l| l.trim() != INCLUDE_LINE)
        .collect::<Vec<_>>()
        .join("\n");
    let updated = updated.trim_start_matches('\n');
    // Preserve a single trailing newline if the original had one.
    let updated = if existing.ends_with('\n') {
        format!("{updated}\n")
    } else {
        updated.to_string()
    };
    write_secure(&config_path, &updated)?;
    Ok(true)
}

// ─── Unresolved user variable helpers ─────────────────────────────────────────

/// Extract all `${key}` tokens from a string, returning the key names.
fn extract_all_template_keys(value: &str) -> Vec<String> {
    let mut keys = Vec::new();
    let mut rest = value;
    while let Some(start) = rest.find("${") {
        let after = &rest[start + 2..];
        if let Some(end) = after.find('}') {
            let key = &after[..end];
            if !key.is_empty() {
                keys.push(key.to_string());
            }
            rest = &after[end + 1..];
        } else {
            break;
        }
    }
    keys
}

/// Scan all connections for `${key}` tokens in user fields that cannot be
/// resolved by inline_overrides or cfg.users. Returns a vec of
/// `(key_name, vec_of_connection_names)` sorted by key name.
fn collect_unresolved_keys(
    cfg: &LoadedConfig,
    inline_overrides: &HashMap<String, String>,
) -> Vec<(String, Vec<String>)> {
    let mut unresolved: HashMap<String, Vec<String>> = HashMap::new();

    for conn in &cfg.connections {
        for key in extract_all_template_keys(&conn.user) {
            // Check if the key can be resolved.
            if inline_overrides.contains_key(&key) {
                continue;
            }
            if cfg.users.contains_key(&key) {
                continue;
            }
            // Special case: ${user} resolves from $USER env var.
            if key == "user" && std::env::var("USER").is_ok() {
                continue;
            }
            unresolved.entry(key).or_default().push(conn.name.clone());
        }
    }

    let mut result: Vec<(String, Vec<String>)> = unresolved.into_iter().collect();
    result.sort_by(|a, b| a.0.cmp(&b.0));
    result
}

/// Resolve the path to the user-layer connections.yaml file.
fn resolve_user_layer_config_path() -> Result<PathBuf> {
    let base = dirs::config_dir()
        .ok_or_else(|| anyhow::anyhow!("cannot determine user config directory"))?;
    Ok(base.join("yconn").join("connections.yaml"))
}

/// Prompt the user for each missing user variable, write to target file, and
/// return the list of `(key, value)` pairs that were written.
fn prompt_missing_keys(
    target_file: &Path,
    missing: &[(String, Vec<String>)],
    input: &mut dyn BufRead,
    output: &mut dyn Write,
) -> Result<Vec<(String, String)>> {
    let mut prompted = Vec::new();

    for (key, conn_names) in missing {
        writeln!(
            output,
            "Missing user variable '${{{key}}}' used by: {}",
            conn_names.join(", ")
        )?;
        write!(output, "  Value for '{key}': ")?;
        output.flush()?;

        let mut line = String::new();
        input.read_line(&mut line)?;
        let value = line.trim().to_string();

        if value.is_empty() {
            bail!("aborted: no value provided for user variable '{key}'");
        }

        write_user_entry(target_file, key, &value)
            .with_context(|| format!("failed to write user entry '{key}'"))?;
        writeln!(
            output,
            "  Added user entry '{key}' to {}",
            target_file.display()
        )?;

        prompted.push((key.clone(), value));
    }

    Ok(prompted)
}

// ─── Command entry points ─────────────────────────────────────────────────────

pub fn run_install(
    cfg: &LoadedConfig,
    renderer: &Renderer,
    dry_run: bool,
    home: &Path,
    inline_overrides: &HashMap<String, String>,
    skip_user: bool,
) -> Result<()> {
    let stdin = io::stdin();
    let stdout = io::stdout();
    run_install_impl(
        cfg,
        renderer,
        dry_run,
        home,
        inline_overrides,
        skip_user,
        &mut stdin.lock(),
        &mut stdout.lock(),
    )
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn run_install_impl(
    cfg: &LoadedConfig,
    renderer: &Renderer,
    dry_run: bool,
    home: &Path,
    inline_overrides: &HashMap<String, String>,
    skip_user: bool,
    input: &mut dyn BufRead,
    output: &mut dyn Write,
) -> Result<()> {
    // Pre-pass: detect unresolved ${key} tokens and prompt for missing values.
    let mut effective_overrides = inline_overrides.clone();
    let missing = collect_unresolved_keys(cfg, &effective_overrides);
    if !missing.is_empty() {
        let user_layer_file = resolve_user_layer_config_path()?;
        let prompted = prompt_missing_keys(&user_layer_file, &missing, input, output)?;
        // Add prompted values to effective_overrides so expand_user_field
        // resolves them without needing to reload config.
        for (key, value) in prompted {
            effective_overrides.insert(key, value);
        }
    }

    // Expand ${<key>} templates in the user field of each connection.
    let mut connections: Vec<Connection> = cfg.connections.clone();
    for conn in &mut connections {
        let (expanded, warnings) = cfg.expand_user_field(&conn.user, &effective_overrides);
        for w in &warnings {
            // Extract the unresolved key from the expanded user field so we can
            // suggest the fix command.  The expanded value still contains the
            // original `${key}` token when the key could not be resolved.
            let fix = extract_unresolved_key(&expanded)
                .map(|key| format!("  Fix: yconn users add --user {key}:<value>"))
                .unwrap_or_default();
            if fix.is_empty() {
                renderer.warn(w);
            } else {
                renderer.warn(&format!("{w}\n{fix}"));
            }
        }
        conn.user = expanded;
    }

    let rendered = render_ssh_config(&connections, skip_user);
    let block_count = connections.len();

    // Parse the newly rendered blocks.
    let new_blocks = parse_host_blocks(&rendered);

    // Read the existing file (if present) and merge.
    let out_path = output_path(home);
    let existing_content = if out_path.exists() {
        fs::read_to_string(&out_path)
            .with_context(|| format!("failed to read {}", out_path.display()))?
    } else {
        String::new()
    };

    let existing_blocks = if existing_content.is_empty() {
        Vec::new()
    } else {
        parse_host_blocks(&existing_content)
    };

    let merged = merge_host_blocks(existing_blocks, new_blocks);

    if dry_run {
        println!("{merged}");
        return Ok(());
    }

    ensure_ssh_dir(home)?;
    write_secure(&out_path, &format!("{merged}\n"))?;
    inject_include(home)?;

    println!(
        "Wrote {block_count} Host block(s) to {}",
        out_path.display()
    );

    Ok(())
}

pub fn run_print(
    cfg: &LoadedConfig,
    renderer: &Renderer,
    _home: &Path,
    inline_overrides: &HashMap<String, String>,
    skip_user: bool,
) -> Result<()> {
    // Expand ${<key>} templates in the user field of each connection.
    let mut connections: Vec<Connection> = cfg.connections.clone();
    for conn in &mut connections {
        let (expanded, warnings) = cfg.expand_user_field(&conn.user, inline_overrides);
        for w in &warnings {
            let fix = extract_unresolved_key(&expanded)
                .map(|key| format!("  Fix: yconn users add --user {key}:<value>"))
                .unwrap_or_default();
            if fix.is_empty() {
                renderer.warn(w);
            } else {
                renderer.warn(&format!("{w}\n{fix}"));
            }
        }
        conn.user = expanded;
    }

    let rendered = render_ssh_config(&connections, skip_user);
    println!("{rendered}");
    Ok(())
}

pub fn run_uninstall(home: &Path) -> Result<()> {
    let out_path = output_path(home);
    if out_path.exists() {
        fs::remove_file(&out_path)
            .with_context(|| format!("failed to remove {}", out_path.display()))?;
        println!("Removed {}", out_path.display());
    } else {
        println!("{} does not exist — nothing to remove", out_path.display());
    }

    if remove_include_line(home)? {
        println!("Removed Include line from ~/.ssh/config");
    } else {
        println!("Include line not present in ~/.ssh/config — nothing to remove");
    }

    Ok(())
}

pub fn run_disable(home: &Path) -> Result<()> {
    if remove_include_line(home)? {
        println!("Removed Include line from ~/.ssh/config");
    } else {
        println!("Include line not present in ~/.ssh/config — nothing to do");
    }
    Ok(())
}

pub fn run_enable(home: &Path) -> Result<()> {
    let config_path = home.join(".ssh").join("config");
    let already_present = config_path.exists() && {
        let existing = fs::read_to_string(&config_path)
            .with_context(|| format!("failed to read {}", config_path.display()))?;
        existing.lines().any(|l| l.trim() == INCLUDE_LINE)
    };

    if already_present {
        println!("Include line already present in ~/.ssh/config — nothing to do");
        return Ok(());
    }

    ensure_ssh_dir(home)?;
    inject_include(home)?;
    println!("Added Include line to ~/.ssh/config");
    Ok(())
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{Auth, Connection, Layer};
    use std::path::PathBuf;

    fn make_conn(
        name: &str,
        host: &str,
        user: &str,
        port: u16,
        auth_type: &str,
        key: Option<&str>,
    ) -> Connection {
        let auth = match auth_type {
            "key" => Auth::Key {
                key: key.unwrap_or("~/.ssh/id_rsa").to_string(),
                cmd: None,
            },
            "identity" => Auth::Identity {
                key: key.unwrap_or("~/.ssh/id_rsa").to_string(),
                cmd: None,
            },
            _ => Auth::Password,
        };
        Connection {
            name: name.to_string(),
            host: host.to_string(),
            user: user.to_string(),
            port,
            auth,
            description: format!("{name} description"),
            link: None,
            group: None,
            layer: Layer::User,
            source_path: PathBuf::from("test.yaml"),
            shadowed: false,
        }
    }

    fn make_conn_with_link(name: &str, link: &str) -> Connection {
        let mut c = make_conn(name, "host.example.com", "user", 22, "password", None);
        c.link = Some(link.to_string());
        c
    }

    #[test]
    fn test_key_auth_block_format() {
        let conn = make_conn(
            "prod-web",
            "10.0.1.50",
            "deploy",
            22,
            "key",
            Some("~/.ssh/id_rsa"),
        );
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("Host prod-web\n"), "missing Host line");
        assert!(out.contains("    HostName 10.0.1.50\n"));
        assert!(out.contains("    User deploy\n"));
        assert!(out.contains("    IdentityFile ~/.ssh/id_rsa\n"));
        assert!(!out.contains("Port"), "port 22 must be omitted");
    }

    #[test]
    fn test_password_auth_block_no_identity_file() {
        let conn = make_conn(
            "staging-db",
            "staging.internal",
            "dbadmin",
            22,
            "password",
            None,
        );
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("Host staging-db\n"));
        assert!(
            !out.contains("IdentityFile"),
            "no IdentityFile for password auth"
        );
    }

    #[test]
    fn test_identity_auth_emits_identity_file_and_identities_only() {
        let conn = make_conn(
            "github",
            "github.com",
            "git",
            22,
            "identity",
            Some("~/.ssh/github_key"),
        );
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("Host github\n"), "missing Host line");
        assert!(out.contains("    HostName github.com\n"));
        assert!(out.contains("    User git\n"));
        assert!(
            out.contains("    IdentityFile ~/.ssh/github_key\n"),
            "identity auth must emit IdentityFile"
        );
        assert!(
            out.contains("    IdentitiesOnly yes\n"),
            "identity auth must emit IdentitiesOnly yes"
        );
        // IdentitiesOnly must appear after IdentityFile.
        let id_file_pos = out.find("IdentityFile").unwrap();
        let id_only_pos = out.find("IdentitiesOnly").unwrap();
        assert!(
            id_only_pos > id_file_pos,
            "IdentitiesOnly must appear after IdentityFile"
        );
    }

    #[test]
    fn test_key_auth_does_not_emit_identities_only() {
        let conn = make_conn(
            "prod-web",
            "10.0.1.50",
            "deploy",
            22,
            "key",
            Some("~/.ssh/id_rsa"),
        );
        let out = render_ssh_config(&[conn], false);
        assert!(
            out.contains("    IdentityFile ~/.ssh/id_rsa\n"),
            "key auth must emit IdentityFile"
        );
        assert!(
            !out.contains("IdentitiesOnly"),
            "key auth must NOT emit IdentitiesOnly"
        );
    }

    #[test]
    fn test_port_22_omitted() {
        let conn = make_conn("srv", "1.2.3.4", "ops", 22, "password", None);
        let out = render_ssh_config(&[conn], false);
        assert!(!out.contains("Port"), "port 22 must not appear");
    }

    #[test]
    fn test_non_22_port_included() {
        let conn = make_conn(
            "bastion",
            "bastion.example.com",
            "ec2-user",
            2222,
            "key",
            Some("~/.ssh/key"),
        );
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("    Port 2222\n"), "custom port must appear");
    }

    #[test]
    fn test_glob_name_rendered_as_ssh_host_pattern() {
        let conn = make_conn("web-*", "${name}.corp.com", "deploy", 22, "password", None);
        let out = render_ssh_config(&[conn], false);
        assert!(
            out.contains("Host web-*\n"),
            "glob must appear as Host pattern"
        );
        assert!(
            out.contains("    HostName %h.corp.com\n"),
            "\\${{name}} must become %h"
        );
        assert!(!out.contains("skipped"));
    }

    #[test]
    fn test_range_pattern_name_translated_to_glob() {
        let conn = make_conn(
            "server[1..10]",
            "${name}.internal",
            "ops",
            22,
            "password",
            None,
        );
        let out = render_ssh_config(&[conn], false);
        assert!(
            out.contains("Host server*\n"),
            "range [N..M] must become * in Host line"
        );
        assert!(
            out.contains("    HostName %h.internal\n"),
            "\\${{name}} must become %h"
        );
        assert!(
            !out.contains("Host server[1..10]"),
            "range must not appear in Host line"
        );
    }

    #[test]
    fn test_name_template_in_host_becomes_percent_h() {
        let conn = make_conn("web-*", "${name}.corp.com", "deploy", 22, "password", None);
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("    HostName %h.corp.com\n"));
        assert!(!out.contains("${name}"));
    }

    #[test]
    fn test_literal_host_unchanged() {
        let conn = make_conn(
            "bastion",
            "bastion.example.com",
            "ec2-user",
            22,
            "key",
            None,
        );
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("    HostName bastion.example.com\n"));
    }

    #[test]
    fn test_remove_include_line_removes_only_include_line() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ssh_dir = tmp.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();
        let config_path = ssh_dir.join("config");
        fs::write(
            &config_path,
            format!("{INCLUDE_LINE}\n\nHost existing\n    HostName 9.9.9.9\n"),
        )
        .unwrap();

        let removed = remove_include_line(tmp.path()).unwrap();
        assert!(removed, "must return true when line was present");

        let result = fs::read_to_string(&config_path).unwrap();
        assert!(
            !result.contains(INCLUDE_LINE),
            "Include line must be removed: {result}"
        );
        assert!(
            result.contains("Host existing"),
            "surrounding content must be preserved: {result}"
        );
        assert!(
            result.contains("    HostName 9.9.9.9"),
            "HostName must be preserved: {result}"
        );
    }

    #[test]
    fn test_remove_include_line_noop_when_absent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ssh_dir = tmp.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();
        let config_path = ssh_dir.join("config");
        fs::write(&config_path, "Host existing\n    HostName 9.9.9.9\n").unwrap();

        let removed = remove_include_line(tmp.path()).unwrap();
        assert!(!removed, "must return false when line was absent");

        let result = fs::read_to_string(&config_path).unwrap();
        assert!(
            result.contains("Host existing"),
            "content must be unchanged: {result}"
        );
    }

    #[test]
    fn test_idempotent_include_injection() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ssh_dir = tmp.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();
        let config_path = ssh_dir.join("config");
        fs::write(
            &config_path,
            format!("{INCLUDE_LINE}\n\nHost old\n    HostName 1.2.3.4\n"),
        )
        .unwrap();

        inject_include(tmp.path()).unwrap();

        let result = fs::read_to_string(&config_path).unwrap();
        let count = result.lines().filter(|l| l.trim() == INCLUDE_LINE).count();
        assert_eq!(count, 1, "Include must appear exactly once");
    }

    #[test]
    fn test_include_prepended_when_absent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ssh_dir = tmp.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();
        let config_path = ssh_dir.join("config");
        fs::write(&config_path, "Host existing\n    HostName 9.9.9.9\n").unwrap();

        inject_include(tmp.path()).unwrap();

        let result = fs::read_to_string(&config_path).unwrap();
        assert!(
            result.starts_with(INCLUDE_LINE),
            "Include must be first line"
        );
        assert!(
            result.contains("Host existing"),
            "existing content preserved"
        );
    }

    #[test]
    fn test_config_created_when_absent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let ssh_dir = tmp.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();

        inject_include(tmp.path()).unwrap();

        let config_path = ssh_dir.join("config");
        assert!(config_path.exists(), "config file must be created");
        let result = fs::read_to_string(&config_path).unwrap();
        assert!(result.contains(INCLUDE_LINE));
    }

    #[test]
    fn test_link_field_appears_in_comment() {
        let conn = make_conn_with_link("srv", "https://wiki.example.com/srv");
        let out = render_ssh_config(&[conn], false);
        assert!(out.contains("# link: https://wiki.example.com/srv"));
        assert!(!out.contains("# yconn:"));
    }

    // ── user field expansion ───────────────────────────────────────────────────

    /// Helper: load config from inline YAML with a users: section, expand user
    /// fields using inline_overrides, and return the rendered SSH config string.
    fn render_expanded(
        yaml: &str,
        inline_overrides: &HashMap<String, String>,
        skip_user: bool,
    ) -> (String, Vec<String>) {
        use crate::config;
        use tempfile::TempDir;

        let user_dir = TempDir::new().unwrap();
        let cwd = TempDir::new().unwrap();
        let sys = TempDir::new().unwrap();
        fs::write(user_dir.path().join("connections.yaml"), yaml).unwrap();

        let cfg = config::load_impl(
            cwd.path(),
            Some("connections"),
            false,
            Some(user_dir.path()),
            sys.path(),
        )
        .unwrap();

        let mut conns: Vec<Connection> = cfg.connections.clone();
        let mut all_warnings: Vec<String> = Vec::new();
        for conn in &mut conns {
            let (expanded, warnings) = cfg.expand_user_field(&conn.user, inline_overrides);
            all_warnings.extend(warnings);
            conn.user = expanded;
        }

        (render_ssh_config(&conns, skip_user), all_warnings)
    }

    #[test]
    fn test_dollar_user_expanded_from_override() {
        // Use --user user:alice override (deterministic, no dependency on $USER env var).
        let yaml = "connections:\n  srv:\n    host: myhost\n    user: \"${user}\"\n    auth:\n      type: password\n    description: test\n";
        let mut overrides = HashMap::new();
        overrides.insert("user".to_string(), "alice".to_string());
        let (out, _warnings) = render_expanded(yaml, &overrides, false);
        assert!(
            out.contains("    User alice\n"),
            "expected 'User alice', got: {out}"
        );
        assert!(!out.contains("${user}"));
    }

    #[test]
    fn test_dollar_user_unresolved_emits_comment_not_user_line() {
        // When expansion leaves ${user} unchanged (no override, env may be set but
        // we test the render path directly with the literal value).
        let conn = make_conn("srv", "myhost", "${user}", 22, "password", None);
        let out = render_ssh_config(&[conn], false);
        // The unresolved token should appear as a comment, not a User directive.
        assert!(
            !out.contains("    User ${user}"),
            "must not render as User line: {out}"
        );
        assert!(
            out.contains("# user: ${user} (unresolved)"),
            "must render as comment: {out}"
        );
    }

    #[test]
    fn test_named_key_expanded_from_users_map() {
        let yaml = "users:\n  testuser: \"ops\"\nconnections:\n  srv:\n    host: myhost\n    user: \"${testuser}\"\n    auth:\n      type: password\n    description: test\n";
        let (out, warnings) = render_expanded(yaml, &HashMap::new(), false);
        assert!(
            out.contains("    User ops\n"),
            "expected 'User ops', got: {out}"
        );
        assert!(warnings.is_empty(), "no warnings expected: {warnings:?}");
    }

    #[test]
    fn test_skip_user_omits_user_line() {
        let conn = make_conn("srv", "myhost", "deploy", 22, "password", None);
        let out = render_ssh_config(&[conn], true);
        assert!(
            !out.contains("User"),
            "User line must be omitted with skip_user: {out}"
        );
    }

    #[test]
    fn test_user_override_overrides_users_map() {
        let yaml = "users:\n  testuser: \"ops\"\nconnections:\n  srv:\n    host: myhost\n    user: \"${testuser}\"\n    auth:\n      type: password\n    description: test\n";
        let mut overrides = HashMap::new();
        overrides.insert("testuser".to_string(), "alice".to_string());
        let (out, warnings) = render_expanded(yaml, &overrides, false);
        assert!(
            out.contains("    User alice\n"),
            "expected 'User alice', got: {out}"
        );
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_multiple_user_overrides_all_applied() {
        let yaml = "users:\n  k1: \"a\"\nconnections:\n  c1:\n    host: h1\n    user: \"${k1}\"\n    auth:\n      type: password\n    description: d1\n  c2:\n    host: h2\n    user: \"${user}\"\n    auth:\n      type: password\n    description: d2\n";
        let mut overrides = HashMap::new();
        overrides.insert("k1".to_string(), "carol".to_string());
        overrides.insert("user".to_string(), "dave".to_string());
        let (out, warnings) = render_expanded(yaml, &overrides, false);
        assert!(
            out.contains("    User carol\n") || out.contains("    User dave\n"),
            "both overrides must be applied: {out}"
        );
        assert!(warnings.is_empty());
    }

    #[test]
    fn test_unresolved_template_produces_warning() {
        let yaml = "connections:\n  srv:\n    host: myhost\n    user: \"${nokey}\"\n    auth:\n      type: password\n    description: test\n";
        let (_out, warnings) = render_expanded(yaml, &HashMap::new(), false);
        assert!(
            !warnings.is_empty(),
            "expected warning for unresolved template"
        );
        assert!(
            warnings[0].contains("unresolved"),
            "warning must say unresolved: {}",
            warnings[0]
        );
    }

    #[test]
    fn test_unresolved_template_warning_contains_fix_command() {
        // run_install enriches warnings with the fix command at its call site.
        // We test extract_unresolved_key directly here, and verify that the
        // enrichment logic produces the expected fix string.
        assert_eq!(
            super::extract_unresolved_key("${t1user}"),
            Some("t1user"),
            "must extract key from simple token"
        );
        assert_eq!(
            super::extract_unresolved_key("${t1user}.suffix"),
            Some("t1user"),
            "must extract key when followed by extra text"
        );
        assert_eq!(
            super::extract_unresolved_key("no_template"),
            None,
            "must return None when no template present"
        );

        // Verify the enriched warning format for a known key.
        let key = super::extract_unresolved_key("${t1user}").unwrap();
        let fix = format!("  Fix: yconn users add --user {key}:<value>");
        assert!(
            fix.contains("yconn users add --user t1user:<value>"),
            "fix command must match expected format: {fix}"
        );
    }

    /// All four comment fields (description, auth, link, unresolved user) must
    /// appear contiguously before the `Host` line, in that order, and no `#`
    /// lines must appear inside the Host block (after `Host` until the next
    /// blank line).
    #[test]
    fn test_all_comment_fields_precede_host_line() {
        let mut conn = make_conn(
            "srv", "myhost", "${nokey}", // unresolved → triggers user comment
            22, "password", None,
        );
        conn.link = Some("https://wiki.example.com/srv".to_string());
        conn.description = "My server".to_string();

        let out = render_ssh_config(&[conn], false);

        // Locate positions.
        let host_pos = out.find("Host srv\n").expect("Host line must be present");
        let desc_pos = out
            .find("# description:")
            .expect("# description must be present");
        let auth_pos = out.find("# auth:").expect("# auth must be present");
        let link_pos = out.find("# link:").expect("# link must be present");
        let user_pos = out
            .find("# user: ${nokey} (unresolved)")
            .expect("# user comment must be present");

        // All comments precede the Host line.
        assert!(desc_pos < host_pos, "# description must precede Host line");
        assert!(auth_pos < host_pos, "# auth must precede Host line");
        assert!(link_pos < host_pos, "# link must precede Host line");
        assert!(
            user_pos < host_pos,
            "# user (unresolved) must precede Host line"
        );

        // Order: description → auth → link → user comment.
        assert!(desc_pos < auth_pos, "# description must come before # auth");
        assert!(auth_pos < link_pos, "# auth must come before # link");
        assert!(
            link_pos < user_pos,
            "# link must come before # user comment"
        );

        // No # lines inside the Host block (between Host line and the trailing blank line).
        let block_body = &out[host_pos..];
        let blank_pos = block_body.find("\n\n").unwrap_or(block_body.len());
        let block_interior = &block_body[..blank_pos];
        // Skip the "Host srv\n" line itself when looking for embedded comments.
        let after_host_line = &block_interior["Host srv\n".len()..];
        assert!(
            !after_host_line.contains("\n#"),
            "no # lines must appear inside the Host block: {after_host_line:?}"
        );
        assert!(
            !after_host_line.starts_with('#'),
            "first line after Host must not be a comment: {after_host_line:?}"
        );
    }

    // ── host block upsert ──────────────────────────────────────────────────────

    /// `parse_host_blocks` returns one block per `Host` line.
    #[test]
    fn test_parse_host_blocks_basic() {
        let content = "# description: prod\n# auth: key\nHost prod-web\n    HostName 10.0.1.50\n    User deploy\n\n# description: db\n# auth: password\nHost staging-db\n    HostName staging.internal\n\n";
        let blocks = parse_host_blocks(content);
        assert_eq!(blocks.len(), 2);
        assert_eq!(blocks[0].ssh_host, "prod-web");
        assert_eq!(blocks[1].ssh_host, "staging-db");
    }

    /// `parse_host_blocks` on an empty string returns no blocks.
    #[test]
    fn test_parse_host_blocks_empty() {
        assert!(parse_host_blocks("").is_empty());
    }

    /// `merge_host_blocks`: existing file has two foreign blocks and one
    /// matching block. The matching block is replaced, the two foreign blocks
    /// are preserved, and the result has three blocks total.
    #[test]
    fn test_merge_preserves_foreign_blocks_and_replaces_matching() {
        let existing_content = "# description: foreign one\n# auth: key\nHost foreign-1\n    HostName f1.example.com\n\n# description: old prod\n# auth: key\nHost prod-web\n    HostName 10.0.0.1\n\n# description: foreign two\n# auth: password\nHost foreign-2\n    HostName f2.example.com\n\n";
        let existing = parse_host_blocks(existing_content);
        assert_eq!(existing.len(), 3);

        // New blocks contain only prod-web (updated).
        let new_content =
            "# description: new prod\n# auth: key\nHost prod-web\n    HostName 10.0.1.50\n";
        let new_blocks = parse_host_blocks(new_content);

        let merged = merge_host_blocks(existing, new_blocks);

        // Three blocks total.
        let result_blocks = parse_host_blocks(&merged);
        assert_eq!(result_blocks.len(), 3, "expected 3 blocks, got: {merged}");

        // Foreign blocks are preserved.
        assert!(
            merged.contains("Host foreign-1"),
            "foreign-1 must be preserved: {merged}"
        );
        assert!(
            merged.contains("Host foreign-2"),
            "foreign-2 must be preserved: {merged}"
        );

        // Matching block is replaced with new content.
        assert!(
            merged.contains("10.0.1.50"),
            "new prod-web HostName must appear: {merged}"
        );
        assert!(
            !merged.contains("10.0.0.1"),
            "old prod-web HostName must be gone: {merged}"
        );

        // Order: foreign-1 first, then prod-web, then foreign-2.
        let pos_f1 = merged.find("Host foreign-1").unwrap();
        let pos_prod = merged.find("Host prod-web").unwrap();
        let pos_f2 = merged.find("Host foreign-2").unwrap();
        assert!(pos_f1 < pos_prod, "foreign-1 must precede prod-web");
        assert!(pos_prod < pos_f2, "prod-web must precede foreign-2");
    }

    /// `merge_host_blocks`: when the existing file is absent (empty blocks),
    /// the output equals the rendered blocks exactly.
    #[test]
    fn test_merge_absent_file_equals_rendered_blocks() {
        let new_content = "# description: prod\n# auth: key\nHost prod-web\n    HostName 10.0.1.50\n    User deploy\n";
        let new_blocks = parse_host_blocks(new_content);

        let merged = merge_host_blocks(Vec::new(), new_blocks);

        // Must contain the rendered block.
        assert!(
            merged.contains("Host prod-web"),
            "prod-web must appear: {merged}"
        );
        assert!(
            merged.contains("    HostName 10.0.1.50"),
            "HostName must appear: {merged}"
        );
    }

    /// `merge_host_blocks`: new blocks not in the existing file are appended
    /// after the existing blocks.
    #[test]
    fn test_merge_new_blocks_appended_after_existing() {
        let existing_content =
            "# description: foreign\n# auth: key\nHost foreign-1\n    HostName f1.example.com\n\n";
        let existing = parse_host_blocks(existing_content);

        let new_content =
            "# description: prod\n# auth: key\nHost prod-web\n    HostName 10.0.1.50\n";
        let new_blocks = parse_host_blocks(new_content);

        let merged = merge_host_blocks(existing, new_blocks);

        let pos_foreign = merged.find("Host foreign-1").unwrap();
        let pos_prod = merged.find("Host prod-web").unwrap();
        assert!(
            pos_foreign < pos_prod,
            "existing foreign block must precede newly appended block"
        );
    }

    /// When `skip_user=true` and the user field is resolved (no template token),
    /// no `#` lines must appear inside the Host block.
    #[test]
    fn test_skip_user_resolved_no_comment_inside_host_block() {
        let conn = make_conn("srv", "myhost", "deploy", 22, "key", Some("~/.ssh/id_rsa"));
        let out = render_ssh_config(&[conn], true);

        let host_pos = out.find("Host srv\n").expect("Host line must be present");
        let block_body = &out[host_pos..];
        let blank_pos = block_body.find("\n\n").unwrap_or(block_body.len());
        let block_interior = &block_body[..blank_pos];
        let after_host_line = &block_interior["Host srv\n".len()..];

        assert!(
            !after_host_line.contains("\n#"),
            "no # lines must appear inside the Host block with skip_user=true: {after_host_line:?}"
        );
        assert!(
            !after_host_line.starts_with('#'),
            "first line after Host must not be a comment: {after_host_line:?}"
        );
        assert!(
            !out.contains("User "),
            "User line must be absent with skip_user=true"
        );
    }

    // ── unresolved user variable prompting in run_install_impl ────────────────

    /// Helper: build a LoadedConfig from user-layer YAML.
    fn load_cfg(yaml: &str) -> (crate::config::LoadedConfig, tempfile::TempDir) {
        use crate::config;
        use tempfile::TempDir;

        let user_dir = TempDir::new().unwrap();
        let cwd = TempDir::new().unwrap();
        let sys = TempDir::new().unwrap();
        fs::write(user_dir.path().join("connections.yaml"), yaml).unwrap();

        let cfg = config::load_impl(
            cwd.path(),
            Some("connections"),
            false,
            Some(user_dir.path()),
            sys.path(),
        )
        .unwrap();

        (cfg, user_dir)
    }

    /// `run_install_impl` with an unresolved `${t1user}` template halts
    /// and prompts. After the user supplies a value, the Host block uses
    /// the resolved value.
    #[test]
    fn test_run_install_impl_unresolved_key_prompts_and_resolves() {
        let yaml = "connections:\n  srv:\n    host: myhost\n    user: \"${t1user}\"\n    auth:\n      type: password\n    description: test\n";
        let (cfg, _user_dir) = load_cfg(yaml);

        let home = tempfile::TempDir::new().unwrap();
        let ssh_dir = home.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();

        let renderer = crate::display::Renderer::new(false);

        let mut input = "alice\n".as_bytes();
        let mut output = Vec::<u8>::new();

        // We need XDG_CONFIG_HOME set for resolve_user_layer_config_path.
        // But the function uses dirs::config_dir() which reads XDG_CONFIG_HOME.
        // In test context, we set it temporarily.
        let xdg_dir = tempfile::TempDir::new().unwrap();
        std::env::set_var("XDG_CONFIG_HOME", xdg_dir.path());

        let result = super::run_install_impl(
            &cfg,
            &renderer,
            false,
            home.path(),
            &HashMap::new(),
            false,
            &mut input,
            &mut output,
        );
        result.unwrap();

        let output_str = String::from_utf8(output).unwrap();
        assert!(
            output_str.contains("Missing user variable '${t1user}' used by: srv"),
            "expected prompt for missing variable, got: {output_str}"
        );
        assert!(
            output_str.contains("Added user entry 't1user'"),
            "expected confirmation, got: {output_str}"
        );

        // Check that the Host block was written with the resolved value.
        let host_blocks =
            fs::read_to_string(home.path().join(".ssh").join("yconn-connections")).unwrap();
        assert!(
            host_blocks.contains("User alice"),
            "expected 'User alice' in Host block, got: {host_blocks}"
        );
    }

    /// `run_install_impl` with all keys already resolved produces no prompts.
    #[test]
    fn test_run_install_impl_resolved_keys_no_prompt() {
        let yaml = "users:\n  t1user: \"bob\"\nconnections:\n  srv:\n    host: myhost\n    user: \"${t1user}\"\n    auth:\n      type: password\n    description: test\n";
        let (cfg, _user_dir) = load_cfg(yaml);

        let home = tempfile::TempDir::new().unwrap();
        let ssh_dir = home.path().join(".ssh");
        fs::create_dir_all(&ssh_dir).unwrap();

        let renderer = crate::display::Renderer::new(false);

        let mut input = "".as_bytes();
        let mut output = Vec::<u8>::new();

        let result = super::run_install_impl(
            &cfg,
            &renderer,
            false,
            home.path(),
            &HashMap::new(),
            false,
            &mut input,
            &mut output,
        );
        result.unwrap();

        let output_str = String::from_utf8(output).unwrap();
        assert!(
            !output_str.contains("Missing user variable"),
            "should not prompt when all keys are resolved, got: {output_str}"
        );

        // Check that the Host block uses the resolved value.
        let host_blocks =
            fs::read_to_string(home.path().join(".ssh").join("yconn-connections")).unwrap();
        assert!(
            host_blocks.contains("User bob"),
            "expected 'User bob' in Host block, got: {host_blocks}"
        );
    }
}