smbcloud-cli 1.2.2

smbCloud command line interface.
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
use {
    crate::{
        cli::CommandResult,
        client,
        deploy::known_hosts,
        ui::{fail_message, fail_symbol, succeed_message, succeed_symbol},
    },
    anyhow::{anyhow, Result},
    base64::{engine::general_purpose::STANDARD as BASE64, Engine as _},
    chrono::Utc,
    smbcloud_auth::me::me,
    smbcloud_model::project::{DeploymentPayload, DeploymentStatus},
    smbcloud_network::environment::Environment,
    smbcloud_networking_project::{
        crud_project_deployment_create::create_deployment, crud_project_deployment_update::update,
    },
    smbcloud_utils::config::Config,
    spinners::{Spinner, Spinners},
    std::{
        collections::HashMap,
        io::Write,
        process::{Command, Stdio},
    },
    tempfile::NamedTempFile,
};

/// Recursively delete symlinks under `root` whose target does not exist,
/// returning the number removed.
///
/// Next.js standalone output on pnpm can contain compat symlinks pointing at a
/// package version that was never traced into the bundle — e.g.
/// `node_modules/.pnpm/node_modules/semver -> ../semver@6.3.1/node_modules/semver`
/// while only `semver@7.x` is actually written. The link's target is missing,
/// so it dangles. We upload `.next/standalone/` with `rsync --copy-links`, which
/// follows every symlink; a dangling one is an IO error → rsync exits 23 and
/// aborts. The dangling package is not part of the traced runtime, so dropping
/// the link is safe. See the `smbcloud-deploy-nextjs` skill for the write-up.
///
/// Real (non-symlink) directories are traversed; a symlinked directory is
/// treated as a leaf and never followed, which also avoids symlink cycles. This
/// relies on pnpm's layout, where every package directory is a real directory
/// reachable directly in the walk (symlinks only ever point *into* it): a
/// dangling link nested under a real dir is always visited and pruned. A
/// dangling link reachable *only* through a valid directory symlink would be
/// skipped, but rsync would follow the same valid link and hit it — that shape
/// does not occur in standalone output.
fn prune_dangling_symlinks(root: &std::path::Path) -> std::io::Result<usize> {
    let meta = std::fs::symlink_metadata(root)?;

    if meta.file_type().is_symlink() {
        // A symlink at the walk root: drop it only if it dangles, never follow.
        // `try_exists` follows the link and reports Ok(false) only when the
        // target is genuinely absent; a real IO error propagates instead of
        // being misread as "dangling".
        if !root.try_exists()? {
            std::fs::remove_file(root)?;
            return Ok(1);
        }
        return Ok(0);
    }

    if !meta.is_dir() {
        return Ok(0);
    }

    let mut removed = 0;
    for entry in std::fs::read_dir(root)? {
        let entry = entry?;
        // `read_dir` file types do not follow symlinks: a link reports as a
        // symlink here, and only real directories report as directories.
        let file_type = entry.file_type()?;
        let path = entry.path();

        if file_type.is_symlink() {
            // `try_exists` follows the link; Ok(false) means the target is
            // missing (dangling). An IO error propagates rather than deleting a
            // link we merely failed to stat.
            if !path.try_exists()? {
                std::fs::remove_file(&path)?;
                removed += 1;
            }
        } else if file_type.is_dir() {
            removed += prune_dangling_symlinks(&path)?;
        }
    }

    Ok(removed)
}

/// Node program run on the host to apply the app's env vars to an existing PM2
/// ecosystem file. It reads the values from `SMB_ENV_B64` (base64 of a JSON
/// object), so no value is ever interpolated into shell source.
///
/// It sets every managed key in `env_production` of the app named
/// `SMB_PM2_APP` (in `{ apps: [...] }` or a bare array, both of which pm2 loads), removes keys the previous deploy managed that are gone now,
/// and records the managed key names (never values) in
/// `.smbcloud-env-keys.json`. Keys nobody told smbCloud about stay untouched.
/// The first rewrite keeps the original as `ecosystem.config.cjs.smbcloud.bak`,
/// because the file is re-serialised and comments do not survive.
const ECOSYSTEM_ENV_MERGE_JS: &str = r#"
var fs = require('fs');
var path = require('path');
var file = 'ecosystem.config.cjs';
var keysFile = '.smbcloud-env-keys.json';
var app = process.env.SMB_PM2_APP;
var vars = JSON.parse(Buffer.from(process.env.SMB_ENV_B64, 'base64').toString('utf8'));
function plain(v) {
  if (typeof v === 'function' || typeof v === 'symbol') return false;
  if (v && typeof v === 'object') return Object.keys(v).every(function (k) { return plain(v[k]); });
  return true;
}
var cfg = require(path.resolve(file));
if (!plain(cfg)) {
  console.error('smbCloud: ' + file + ' contains functions, so env vars cannot be merged into it safely. Edit it by hand or remove the functions.');
  process.exit(1);
}
var apps = Array.isArray(cfg) ? cfg : (cfg.apps || []);
var entry = apps.filter(function (a) { return a.name === app; })[0];
if (!entry) {
  console.error('smbCloud: no app named ' + app + ' in ' + file + '.');
  process.exit(1);
}
entry.env_production = entry.env_production || {};
var previous = [];
try { previous = JSON.parse(fs.readFileSync(keysFile, 'utf8')); } catch (e) {}
previous.forEach(function (k) { if (!Object.prototype.hasOwnProperty.call(vars, k)) delete entry.env_production[k]; });
Object.keys(vars).forEach(function (k) { entry.env_production[k] = vars[k]; });
if (!fs.existsSync(file + '.smbcloud.bak')) fs.copyFileSync(file, file + '.smbcloud.bak');
fs.writeFileSync(file, 'module.exports = ' + JSON.stringify(cfg, null, 2) + ';\n');
fs.writeFileSync(keysFile, JSON.stringify(Object.keys(vars).sort()) + '\n');
"#;

/// Shell that applies `pm2_env` to the host's ecosystem file on every deploy.
///
/// Returns an empty string when the server sent no env map at all (`None`),
/// so a failed lookup never strips keys. An empty map is authoritative: the
/// merge still runs when a previous deploy recorded managed keys, to remove
/// them. Needs `PM2_APP` set in the surrounding script.
pub(super) fn ecosystem_env_merge_snippet(
    pm2_env: Option<&HashMap<String, serde_json::Value>>,
) -> String {
    let Some(pm2_env) = pm2_env else {
        return String::new();
    };
    // The deploy sets these itself; the API rejects them, and a stale local
    // config must not override the port the restart stanza passes.
    let vars: std::collections::BTreeMap<&str, String> = pm2_env
        .iter()
        .filter(|(k, _)| !matches!(k.as_str(), "NODE_ENV" | "PORT" | "HOSTNAME"))
        .map(|(k, v)| {
            let value = match v {
                serde_json::Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            (k.as_str(), value)
        })
        .collect();
    let blob = BASE64.encode(serde_json::to_string(&vars).unwrap_or_else(|_| "{}".to_string()));
    let guard = if vars.is_empty() {
        r#"[ -f ecosystem.config.cjs ] && [ -f .smbcloud-env-keys.json ]"#
    } else {
        r#"[ -f ecosystem.config.cjs ]"#
    };
    format!(
        r#"# Apply smbCloud env vars to the ecosystem file on every deploy.
    if {guard}; then
        SMB_PM2_APP="$PM2_APP" SMB_ENV_B64='{blob}' node --input-type=commonjs - << 'SMB_ENV_EOF'
{js}SMB_ENV_EOF
    fi
"#,
        js = ECOSYSTEM_ENV_MERGE_JS.trim_start_matches('\n'),
    )
}

/// Build the shell snippet that (re)starts the app after the standalone bundle
/// is on the server.
///
/// Two supervisors are supported, selected by `process_manager` (matched
/// case-insensitively):
/// - `None` / `"pm2"` → **pm2** (default): delete + start fresh, preferring an
///   operator-managed `ecosystem.config.cjs`/`.js`, else `pm2 start node --
///   server.js` with `PORT`/`HOSTNAME` inline.
/// - `"systemd"` → a **git-owned `systemctl --user` service** named
///   `<pm2_app>.service` (created out-of-band; see the smbcloud-deploy-nextjs
///   skill). Restarted with no sudo — the deploy SSHes as the git app-owner,
///   and `systemctl --user` (with `XDG_RUNTIME_DIR` set) drives that user's own
///   manager. Fails loudly if the unit does not exist.
///
/// Any other value is a hard error rather than a silent fall back to pm2: on an
/// app already migrated to systemd, a typo like `system` would otherwise start
/// a second pm2 process that collides with the systemd-owned port — the exact
/// double-supervisor outage this option exists to prevent.
///
/// The returned snippet references the shell var `$PM2_APP` (set earlier in the
/// deploy script). `port` is only used by the pm2 path.
pub(super) fn restart_stanza(process_manager: Option<&str>, port: u16) -> Result<String> {
    let use_systemd = match process_manager.map(str::trim) {
        None | Some("") => false,
        Some(m) if m.eq_ignore_ascii_case("pm2") => false,
        Some(m) if m.eq_ignore_ascii_case("systemd") => true,
        Some(other) => {
            return Err(anyhow!(fail_message(&format!(
                "Unknown process_manager '{other}' in .smb/config.toml. \
                 Expected \"pm2\" (default) or \"systemd\"."
            ))))
        }
    };

    Ok(if use_systemd {
        r#"    echo "Restarting $PM2_APP via systemd --user…"
    export XDG_RUNTIME_DIR="/run/user/$(id -u)"
    UNIT="$PM2_APP.service"
    if ! systemctl --user cat "$UNIT" >/dev/null 2>&1; then
        echo "Error: systemd --user unit $UNIT not found on the server."
        echo "Create ~/.config/systemd/user/$UNIT and enable it (see the"
        echo "smbcloud-deploy-nextjs skill, 'Process manager: systemd --user'),"
        echo "or unset process_manager to stay on pm2. Then re-deploy."
        exit 1
    fi
    systemctl --user restart "$UNIT"
    sleep 3
    if ! systemctl --user is-active "$UNIT" >/dev/null 2>&1; then
        echo "Error: $UNIT failed to become active after restart."
        systemctl --user status "$UNIT" --no-pager 2>&1 | head -20 || true
        exit 1
    fi
    echo "Done."
"#
        .to_string()
    } else {
        format!(
            r#"    echo "Starting $PM2_APP with pm2..."
    if pm2 describe "$PM2_APP" > /dev/null 2>&1; then
        pm2 delete "$PM2_APP"
    fi

    if [ -f ecosystem.config.cjs ]; then
        pm2 start ecosystem.config.cjs --only "$PM2_APP" --env production
    elif [ -f ecosystem.config.js ]; then
        pm2 start ecosystem.config.js --only "$PM2_APP" --env production
    else
        NODE_ENV=production PORT={port} HOSTNAME=127.0.0.1 pm2 start node --name "$PM2_APP" -- server.js
    fi

    pm2 save
    echo "Done."
"#
        )
    })
}

/// Deploys a Next.js SSR app using standalone output mode.
///
/// Requires `output: 'standalone'` in next.config.js. This produces a
/// self-contained `.next/standalone/` directory that includes only the
/// production Node.js dependencies needed to run the server — no
/// project-level `node_modules` upload required.
///
/// Steps:
///   1. `pnpm install --ignore-scripts`
///   2. `pnpm build`
///   3. POST deployment record as Started
///   4. rsync .next/standalone/  → server:path/          (server + bundled deps)
///   5. rsync .next/static/      → server:path/.next/static/  (static chunks)
///   6. rsync public/            → server:path/public/   (public assets)
///   7. SSH: restart the app — pm2 (default) or a git-owned systemd --user
///      service when `process_manager = "systemd"` (see `restart_stanza`)
///   8. PATCH deployment record as Done
pub async fn process_deploy_nextjs_ssr(env: Environment, config: Config) -> Result<CommandResult> {
    let source = config.project.source.as_deref().unwrap_or(".");
    let package_manager = config.project.package_manager.as_deref().unwrap_or("pnpm");

    let remote_path = config.project.path.as_deref().ok_or_else(|| {
        anyhow!(fail_message(
            "path not set in .smb/config.toml (e.g. path = \"apps/web/myapp\")"
        ))
    })?;

    let pm2_app = config.project.pm2_app.as_deref().ok_or_else(|| {
        anyhow!(fail_message(
            "pm2_app not set in .smb/config.toml (e.g. pm2_app = \"my-app\")"
        ))
    })?;

    let access_token = crate::token::get_smb_token::get_smb_token(env)?;
    let user = me(env, client(), &access_token).await?;

    // ── Step 1: pnpm install --ignore-scripts ────────────────────────────────

    let source_dir = std::path::Path::new(source);
    if !source_dir.exists() {
        return Err(anyhow!(fail_message(&format!(
            "Source path '{}' does not exist. Check the 'source' field in .smb/config.toml.",
            source
        ))));
    }

    let mut install_spinner = Spinner::new(
        Spinners::SimpleDotsScrolling,
        succeed_message(&format!("Installing dependencies in {}…", source)),
    );

    // Capture stdout/stderr so pnpm's output does not interleave with the
    // spinner animation. On failure the captured output is printed for the user.
    let mut install_command = Command::new(package_manager);
    install_command.args(["install", "--ignore-scripts"]);
    // With stdio captured pnpm has no TTY, so when it needs to recreate
    // node_modules (store or linker change) it aborts with
    // ERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTY instead of prompting.
    // CI=true would also skip the prompt, but it turns on --frozen-lockfile.
    // Matching on the file stem also catches full paths and Windows `pnpm.cmd`.
    let is_pnpm = std::path::Path::new(package_manager)
        .file_stem()
        .is_some_and(|stem| stem.eq_ignore_ascii_case("pnpm"));
    if is_pnpm {
        install_command.arg("--config.confirm-modules-purge=false");
    }
    let install_output = install_command.current_dir(source).output().map_err(|e| {
        anyhow!(fail_message(&format!(
            "Failed to spawn '{} install': {}",
            package_manager, e
        )))
    })?;

    if !install_output.status.success() {
        install_spinner.stop_and_persist(&fail_symbol(), fail_message("Install failed."));
        let stderr = String::from_utf8_lossy(&install_output.stderr);
        let stdout = String::from_utf8_lossy(&install_output.stdout);
        let details = if !stderr.trim().is_empty() {
            stderr
        } else {
            stdout
        };
        if !details.trim().is_empty() {
            eprintln!("{}", details.trim());
        }
        return Err(anyhow!(fail_message(&format!(
            "'{} install --ignore-scripts' exited with status {}",
            package_manager, install_output.status
        ))));
    }

    install_spinner.stop_and_persist(
        &succeed_symbol(),
        succeed_message("Dependencies installed."),
    );

    // ── Step 2: pnpm build ───────────────────────────────────────────────────
    // No spinner — Next.js writes its own rich progress output to the terminal.
    // Blank lines before and after keep it visually separated from our log lines.

    println!();

    let build_status = Command::new(package_manager)
        .arg("build")
        .current_dir(source)
        .status()
        .map_err(|e| {
            anyhow!(fail_message(&format!(
                "Failed to spawn '{} build': {}",
                package_manager, e
            )))
        })?;

    println!();

    if !build_status.success() {
        return Err(anyhow!(fail_message(&format!(
            "'{} build' exited with status {}",
            package_manager, build_status
        ))));
    }

    println!(
        "{} {}",
        succeed_symbol(),
        succeed_message("Build complete.")
    );

    // ── Step 3: verify standalone output exists ──────────────────────────────
    //
    // If output: 'standalone' is missing from next.config.js the build
    // succeeds but .next/standalone/ is never created.

    let standalone_dir = format!("{}/.next/standalone", source);
    let standalone_path = std::path::Path::new(&standalone_dir);
    if !standalone_path.exists() {
        return Err(anyhow!(fail_message(
            ".next/standalone not found. Add `output: 'standalone'` to next.config.js and rebuild."
        )));
    }

    let runtime_subdir = if source != "." && standalone_path.join(source).join("server.js").exists()
    {
        Some(source.trim_end_matches('/').to_owned())
    } else {
        None
    };

    // ── Step 3b: prune dangling symlinks from the standalone tree ─────────────
    //
    // The standalone upload uses `rsync --copy-links` (see the Transfer for
    // `.next/standalone/`), which follows every symlink. pnpm can leave compat
    // symlinks whose target was never traced into the bundle; following one is
    // an IO error that makes rsync exit 23 and abort the whole deploy. Drop them
    // now — after the build, before upload — since they are not runtime files.
    match prune_dangling_symlinks(standalone_path) {
        Ok(0) => {}
        Ok(n) => println!(
            "{} {}",
            succeed_symbol(),
            succeed_message(&format!(
                "Pruned {} dangling symlink{} from .next/standalone before upload.",
                n,
                if n == 1 { "" } else { "s" }
            ))
        ),
        Err(e) => {
            return Err(anyhow!(fail_message(&format!(
                "Failed to prune dangling symlinks from .next/standalone: {}",
                e
            ))));
        }
    }

    // ── Step 4: record deployment as Started ─────────────────────────────────

    let deploy_ref = Utc::now().format("%Y%m%dT%H%M%SZ").to_string();

    let created_deployment = create_deployment(
        env,
        client(),
        &access_token,
        config.project.id,
        DeploymentPayload {
            commit_hash: deploy_ref.clone(),
            status: DeploymentStatus::Started,
            frontend_app_id: config.project.frontend_app_id.clone(),
        },
    )
    .await
    .ok();

    // ── Steps 5–7: rsync three items to the server ───────────────────────────
    //
    // Standalone mode produces everything needed to run the server:
    //
    //   .next/standalone/  — server.js + bundled production deps (no project node_modules upload)
    //   .next/static/      — client-side chunks (must be copied into standalone manually)
    //   public/            — static assets served directly by Next.js
    //
    // The static and public dirs must sit inside the standalone tree so
    // `node server.js` can find them at runtime.

    let runner = config.project.runner;
    let rsync_host = runner.rsync_host();

    let home = dirs::home_dir().ok_or_else(|| anyhow!("Could not determine home directory"))?;
    let identity_file = home.join(".ssh").join(format!("id_{}@smbcloud", user.id));
    let identity_file_str = identity_file.to_string_lossy().into_owned();

    // Write pinned known_hosts once for all rsync calls.
    let mut known_hosts_file = NamedTempFile::new()
        .map_err(|e| anyhow!("Failed to create temp known_hosts file: {}", e))?;
    writeln!(known_hosts_file, "{}", known_hosts::for_host(&rsync_host))
        .map_err(|e| anyhow!("Failed to write known_hosts: {}", e))?;

    let ssh_command = format!(
        "ssh -i {identity} \
         -o StrictHostKeyChecking=yes \
         -o UserKnownHostsFile={known_hosts} \
         -o IdentitiesOnly=yes \
         -o PasswordAuthentication=no \
         -o BatchMode=yes",
        identity = identity_file_str,
        known_hosts = known_hosts_file.path().display(),
    );

    let remote_base = format!(
        "git@{}:{}",
        rsync_host,
        if remote_path.ends_with('/') {
            remote_path.to_owned()
        } else {
            format!("{}/", remote_path)
        }
    );

    struct Transfer {
        local_rel: &'static str,
        remote_rel: String,
        protect_runtime_files: bool,
        copy_links: bool,
    }

    let runtime_prefix = runtime_subdir
        .as_ref()
        .map(|path| format!("{}/", path))
        .unwrap_or_default();

    // Next.js copies the project's .env* files into .next/standalone/, so an
    // unfiltered upload would ship the developer's local (often development)
    // env straight into the production runtime directory — and `--delete`
    // would remove any operator-managed .env on the server. Env files are
    // excluded on both sides: local ones never upload, server ones survive
    // (rsync does not delete excluded destination files without
    // --delete-excluded). Runtime env is server-managed — ecosystem config or
    // a server-side .env. Anchored to the app roots so bundled node_modules
    // content is not affected.
    let env_file_excludes: Vec<String> = {
        let mut patterns = vec!["/.env*".to_string()];
        if !runtime_prefix.is_empty() {
            patterns.push(format!("/{}.env*", runtime_prefix));
        }
        patterns
    };

    let local_env_file = [
        format!("{}/.env", standalone_dir),
        format!("{}/{}.env", standalone_dir, runtime_prefix),
    ]
    .iter()
    .any(|path| std::path::Path::new(path).exists());
    if local_env_file {
        println!(
            "{} {}",
            succeed_symbol(),
            succeed_message(
                "Local .env* files found in the standalone build — not uploaded. \
                 Runtime env comes from the server (ecosystem config or server-side .env).",
            )
        );
    }

    // (local_source, remote_destination)
    // .next/standalone contents go to the root of remote_path.
    // .next/static and public go into the runtime directory that contains
    // server.js. When outputFileTracingRoot points above the app directory,
    // Next preserves the source path inside `.next/standalone/`.
    let transfers = vec![
        // standalone contents → remote root
        Transfer {
            local_rel: ".next/standalone/",
            remote_rel: String::new(),
            // pnpm leaves symlinked package entries in standalone output. The
            // server only receives this tree, so those symlinks must be
            // dereferenced during upload. Dangling links (targets never traced
            // into the bundle) are pruned in step 3b so this does not exit 23.
            copy_links: true,
            // The server copy of ecosystem.config.cjs (or .js) is operator-managed
            // runtime config and must survive deploys. Without this protection,
            // rsync `--delete` removes it because it does not exist in
            // .next/standalone/.
            protect_runtime_files: true,
        },
        // static chunks → runtime/.next/static/
        Transfer {
            local_rel: ".next/static/",
            remote_rel: format!("{}.next/static/", runtime_prefix),
            protect_runtime_files: false,
            copy_links: false,
        },
        // public assets → runtime/public/
        Transfer {
            local_rel: "public/",
            remote_rel: format!("{}public/", runtime_prefix),
            protect_runtime_files: false,
            copy_links: false,
        },
    ];

    let mut upload_spinner = Spinner::new(
        Spinners::Hamburger,
        succeed_message(&format!("Uploading to {}…", remote_path)),
    );

    for transfer in transfers {
        let local_path = format!("{}/{}", source, transfer.local_rel);
        let destination = format!("{}{}", remote_base, transfer.remote_rel);

        if !std::path::Path::new(&local_path).exists() {
            continue;
        }

        let mut rsync_args = vec!["-az".to_string(), "--delete".to_string()];

        if transfer.copy_links {
            rsync_args.push("--copy-links".to_string());
        }

        if transfer.protect_runtime_files {
            rsync_args.extend([
                "--exclude".to_string(),
                "ecosystem.config.js".to_string(),
                "--exclude".to_string(),
                "ecosystem.config.cjs".to_string(),
                "--exclude".to_string(),
                "logs/".to_string(),
            ]);
            for pattern in &env_file_excludes {
                rsync_args.extend(["--exclude".to_string(), pattern.clone()]);
            }
        }

        rsync_args.extend([
            "-e".to_string(),
            ssh_command.clone(),
            local_path.clone(),
            destination,
        ]);

        let output = Command::new("rsync")
            .args(&rsync_args)
            .output()
            .map_err(|e| anyhow!(fail_message(&format!("Failed to launch rsync: {}", e))))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            upload_spinner.stop_and_persist(&fail_symbol(), fail_message("Upload failed."));
            mark_failed(
                &deploy_ref,
                &created_deployment,
                &config,
                env,
                &access_token,
            )
            .await;
            return Err(anyhow!(fail_message(&format!(
                "rsync of '{}' failed (status {}): {}",
                transfer.local_rel,
                output.status.code().unwrap_or(-1),
                stderr.trim()
            ))));
        }
    }

    // known_hosts_file must stay alive until all rsync calls complete.
    drop(known_hosts_file);

    upload_spinner.stop_and_persist(&succeed_symbol(), succeed_message("Upload complete."));

    // ── Step 8: SSH remote restart ───────────────────────────────────────────
    //
    // Runs the deployed app via pm2 inside the standalone directory.
    //
    // We always delete the existing pm2 process (if any) and start fresh. A
    // bare `pm2 restart` would re-execute the old command (e.g. `next start
    // --port XXXX` from a previous git-push deploy), which fails when the
    // working directory now contains standalone output instead of the full
    // Next.js build tree.
    //
    // If the server has an operator-managed ecosystem config (.cjs or .js),
    // prefer it as the source of truth for runtime env and pm2 settings. Otherwise fall back
    // to `node server.js` with the minimal inline env needed to bind the app.
    //
    // The port defaults to 3000 and can be overridden with `port = XXXX` in
    // .smb/config.toml — it must match the nginx upstream configuration.

    let port = config.project.port.unwrap_or(3000);
    let runtime_subdir_for_shell = runtime_subdir.clone().unwrap_or_default();

    // Build the ecosystem.config.cjs content from server-side pm2_env, if available.
    // Injected into the deploy script and written only when no config file exists yet.
    let ecosystem_config_content = {
        let mut env_entries = format!(
            r#"        NODE_ENV: "production",
        PORT: {port},
        HOSTNAME: "127.0.0.1",
"#
        );
        if let Some(pm2_env) = &config.project.pm2_env {
            for (key, value) in pm2_env {
                // Skip keys already emitted above
                if key == "NODE_ENV" || key == "PORT" || key == "HOSTNAME" {
                    continue;
                }
                let val_str = match value {
                    serde_json::Value::String(s) => {
                        let escaped = s
                            .replace('\\', "\\\\")
                            .replace('"', "\\\"")
                            .replace('\n', "\\n")
                            .replace('\r', "\\r");
                        format!(r#""{escaped}""#)
                    }
                    other => other.to_string(),
                };
                env_entries.push_str(&format!("        {key}: {val_str},\n"));
            }
        }
        format!(
            r#"module.exports = {{
  apps: [
    {{
      name: "{pm2_app}",
      script: "server.js",
      cwd: "",  // filled at runtime via $APP_PATH
      env_production: {{
{env_entries}      }},
    }},
  ],
}};
"#
        )
    };

    let env_merge = ecosystem_env_merge_snippet(config.project.pm2_env.as_ref());

    // Runtime supervisor: pm2 (default) or a git-owned systemd --user service.
    let restart_stanza = restart_stanza(config.project.process_manager.as_deref(), port)?;

    let deploy_script = format!(
        r#"set -e
    APP_PATH="{remote_path}"
    PM2_APP="{pm2_app}"
    RUNTIME_SUBDIR="{runtime_subdir}"

    case "$APP_PATH" in
        /*) ;;
        *) APP_PATH="$HOME/$APP_PATH" ;;
    esac

    if [ ! -d "$APP_PATH" ]; then
        echo "Error: $APP_PATH is not a directory."
        exit 1
    fi

    cd "$APP_PATH"
    mkdir -p logs

    # Migrate legacy ecosystem.config.js to .cjs so it works when
    # package.json has "type": "module".
    if [ -f ecosystem.config.js ] && [ ! -f ecosystem.config.cjs ]; then
        mv ecosystem.config.js ecosystem.config.cjs
    fi

    # Write ecosystem.config.cjs from smbCloud server config if none exists yet.
    if [ ! -f ecosystem.config.cjs ] && [ ! -f ecosystem.config.js ]; then
        cat > ecosystem.config.cjs << 'ECOSYSTEM_EOF'
{ecosystem_config}
ECOSYSTEM_EOF
        # Patch the cwd field to the actual runtime path
        node --input-type=commonjs -e "
          var fs = require('fs');
          var src = fs.readFileSync('ecosystem.config.cjs', 'utf8');
          src = src.replace('cwd: \"\"', 'cwd: \"' + process.argv[1] + '\"');
          fs.writeFileSync('ecosystem.config.cjs', src);
        " "$APP_PATH" 2>/dev/null || true
    fi

    {env_merge}
    # The monorepo root package.json may declare "type": "module", which
    # Next.js copies into .next/standalone/. Standalone server.js and our
    # shims use require() (CJS). Strip the field so Node treats .js as CJS.
    if [ -f package.json ] && grep -q '"type"' package.json; then
        node --input-type=commonjs -e "
          var fs = require('fs');
          var p = JSON.parse(fs.readFileSync('package.json','utf8'));
          delete p.type;
          fs.writeFileSync('package.json', JSON.stringify(p,null,2)+'\\n');
        " 2>/dev/null || sed -i '"'"'"type".*"module"'"'d' package.json
    fi

    # pnpm standalone output buries peer deps inside node_modules/.pnpm/
    # without the top-level symlinks Node needs for require.resolve().
    # First mirror pnpm's own virtual node_modules directory when it exists —
    # this preserves the exact version selection pnpm already resolved, which is
    # especially important for scoped packages like @swc/helpers.
    # Then fall back to scanning individual .pnpm store entries for anything the
    # virtual directory did not expose.
    if [ -d "node_modules/.pnpm/node_modules" ]; then
        for pkg_path in node_modules/.pnpm/node_modules/*; do
            [ -e "$pkg_path" ] || continue
            pkg_name=$(basename "$pkg_path")
            if [ "${{pkg_name:0:1}}" = "@" ] && [ -d "$pkg_path" ]; then
                mkdir -p "node_modules/$pkg_name"
                for sub_path in "$pkg_path"/*; do
                    [ -e "$sub_path" ] || continue
                    sub_name=$(basename "$sub_path")
                    rm -rf "node_modules/$pkg_name/$sub_name"
                    ln -sfn "$APP_PATH/$sub_path" "node_modules/$pkg_name/$sub_name"
                done
            else
                rm -rf "node_modules/$pkg_name"
                ln -sfn "$APP_PATH/$pkg_path" "node_modules/$pkg_name"
            fi
        done
    fi

    if [ -d "node_modules/.pnpm" ]; then
        find node_modules/.pnpm -mindepth 2 -maxdepth 2 -type d -name "node_modules" 2>/dev/null | while read pnpm_nm; do
            for pkg_path in "$pnpm_nm"/*; do
                [ -e "$pkg_path" ] || continue
                pkg_name=$(basename "$pkg_path")
                if [ "${{pkg_name:0:1}}" = "@" ] && [ -d "$pkg_path" ]; then
                    mkdir -p "node_modules/$pkg_name"
                    for sub_path in "$pkg_path"/*; do
                        [ -e "$sub_path" ] || continue
                        sub_name=$(basename "$sub_path")
                        # Count files in this .pnpm store entry.
                        entry_files=$(find "$sub_path" -maxdepth 2 -type f 2>/dev/null | wc -l | tr -d ' ')
                        existing="node_modules/$pkg_name/$sub_name"
                        if [ -e "$existing" ]; then
                            # Only replace if existing has fewer files than the .pnpm store entry.
                            existing_files=$(find "$existing" -maxdepth 2 -type f 2>/dev/null | wc -l | tr -d ' ')
                            if [ "$entry_files" -gt "$existing_files" ]; then
                                rm -rf "$existing"
                                ln -sfn "$APP_PATH/$sub_path" "$existing"
                            fi
                        else
                            ln -sfn "$APP_PATH/$sub_path" "$existing"
                        fi
                    done
                else
                    if [ -e "node_modules/$pkg_name" ]; then
                        continue
                    fi
                    ln -sfn "$APP_PATH/$pkg_path" "node_modules/$pkg_name"
                fi
            done
        done
    fi

    if [ -n "$RUNTIME_SUBDIR" ]; then
        cat > server.js <<EOF
import("./$RUNTIME_SUBDIR/server.js").catch(function(e){{console.error(e);process.exit(1)}})
EOF
    fi

    # Backward compatibility: older operator-managed ecosystem config files
    # may still point PM2 at `server.js` or `.next/standalone/server.js` in the
    # app root even when standalone preserves the source path inside `web/`.
    mkdir -p .next/standalone
    rm -rf .next/standalone/node_modules
    ln -sfn ../../node_modules .next/standalone/node_modules

    if [ -n "$RUNTIME_SUBDIR" ]; then
        cat > .next/standalone/server.js <<EOF
import("../../$RUNTIME_SUBDIR/server.js").catch(function(e){{console.error(e);process.exit(1)}})
EOF
    else
        ln -sfn ../../server.js .next/standalone/server.js
    fi

{restart}    "#,
        remote_path = remote_path,
        pm2_app = pm2_app,
        runtime_subdir = runtime_subdir_for_shell,
        restart = restart_stanza,
        ecosystem_config = ecosystem_config_content,
        env_merge = env_merge,
    );

    let mut restart_spinner = Spinner::new(
        Spinners::SimpleDotsScrolling,
        succeed_message(&format!("Restarting {} on server…", pm2_app)),
    );

    // Fresh known_hosts file for the SSH exec (previous one was dropped).
    let mut ssh_known_hosts_file = NamedTempFile::new()
        .map_err(|e| anyhow!("Failed to create temp known_hosts file: {}", e))?;
    writeln!(
        ssh_known_hosts_file,
        "{}",
        known_hosts::for_host(&rsync_host)
    )
    .map_err(|e| anyhow!("Failed to write known_hosts: {}", e))?;

    let mut child = Command::new("ssh")
        .args([
            "-i",
            &identity_file_str,
            "-o",
            "StrictHostKeyChecking=yes",
            "-o",
            &format!(
                "UserKnownHostsFile={}",
                ssh_known_hosts_file.path().display()
            ),
            "-o",
            "IdentitiesOnly=yes",
            "-o",
            "PasswordAuthentication=no",
            "-o",
            "BatchMode=yes",
            &format!("git@{}", rsync_host),
            "bash -s",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| anyhow!(fail_message(&format!("Failed to spawn SSH: {}", e))))?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(deploy_script.as_bytes())
            .map_err(|e| anyhow!("Failed to write deploy script to SSH stdin: {}", e))?;
    }

    // stdin was dropped at the end of the if-let block above, sending EOF to
    // remote bash. wait_with_output() reads stdout/stderr then waits for exit.
    let ssh_output = child
        .wait_with_output()
        .map_err(|e| anyhow!("Failed to wait for SSH process: {}", e))?;

    drop(ssh_known_hosts_file);

    if !ssh_output.status.success() {
        restart_spinner.stop_and_persist(&fail_symbol(), fail_message("Remote restart failed."));
        let stderr = String::from_utf8_lossy(&ssh_output.stderr);
        let stdout = String::from_utf8_lossy(&ssh_output.stdout);
        let details = if !stderr.trim().is_empty() {
            stderr
        } else {
            stdout
        };
        if !details.trim().is_empty() {
            eprintln!("{}", details.trim());
        }
        mark_failed(
            &deploy_ref,
            &created_deployment,
            &config,
            env,
            &access_token,
        )
        .await;
        return Err(anyhow!(fail_message(&format!(
            "SSH deploy script exited with status {}",
            ssh_output.status
        ))));
    }

    restart_spinner.stop_and_persist(
        &succeed_symbol(),
        succeed_message(&format!("{} restarted.", pm2_app)),
    );

    // ── Step 9: mark deployment as Done ──────────────────────────────────────

    if let Some(ref deployment) = created_deployment {
        match update(
            env,
            client(),
            access_token,
            config.project.id,
            deployment.id,
            DeploymentPayload {
                commit_hash: deploy_ref,
                status: DeploymentStatus::Done,
                frontend_app_id: config.project.frontend_app_id.clone(),
            },
        )
        .await
        {
            Ok(_) => println!("App is running {}", succeed_symbol()),
            Err(e) => eprintln!("Error updating deployment status to Done: {}", e),
        }
    }

    Ok(CommandResult {
        spinner: Spinner::new(Spinners::Hamburger, String::new()),
        symbol: succeed_symbol(),
        msg: succeed_message("Deployment complete."),
    })
}

/// Mark the in-flight deployment record as Failed.
/// Called on any early-return error path so the dashboard reflects reality.
pub(super) async fn mark_failed(
    deploy_ref: &str,
    created_deployment: &Option<smbcloud_model::project::Deployment>,
    config: &Config,
    env: Environment,
    access_token: &str,
) {
    if let Some(ref deployment) = created_deployment {
        let _ = update(
            env,
            client(),
            access_token.to_owned(),
            config.project.id,
            deployment.id,
            DeploymentPayload {
                commit_hash: deploy_ref.to_owned(),
                status: DeploymentStatus::Failed,
                frontend_app_id: config.project.frontend_app_id.clone(),
            },
        )
        .await;
    }
}

#[cfg(all(test, unix))]
mod tests {
    use {
        super::{ecosystem_env_merge_snippet, prune_dangling_symlinks, restart_stanza},
        serde_json::{json, Value},
        std::{collections::HashMap, os::unix::fs::symlink, path::Path, process::Command},
        tempfile::tempdir,
    };

    /// Mirrors the real failure: a pnpm compat link points at a version dir that
    /// was never traced into the bundle, so it dangles and must be pruned, while
    /// a valid link and real files are left untouched.
    #[test]
    fn prunes_dangling_but_keeps_valid_links_and_files() {
        let root = tempdir().unwrap();
        let base = root.path();

        // Nested real dir mirroring node_modules/.pnpm/node_modules/
        let nm = base.join("node_modules/.pnpm/node_modules");
        std::fs::create_dir_all(&nm).unwrap();

        // A traced package dir + a valid symlink to it.
        let real_pkg = base.join("node_modules/.pnpm/semver@7.7.3/node_modules/semver");
        std::fs::create_dir_all(&real_pkg).unwrap();
        std::fs::write(real_pkg.join("index.js"), "module.exports = {}").unwrap();
        let valid_link = nm.join("valid");
        symlink("../semver@7.7.3/node_modules/semver", &valid_link).unwrap();

        // The dangling compat link: target version was never written.
        let dangling = nm.join("semver");
        symlink("../semver@6.3.1/node_modules/semver", &dangling).unwrap();

        // A plain file that must survive.
        let keeper = base.join("server.js");
        std::fs::write(&keeper, "// server").unwrap();

        let removed = prune_dangling_symlinks(base).unwrap();

        assert_eq!(removed, 1, "exactly the dangling link should be removed");
        assert!(!dangling.exists(), "dangling link is gone");
        assert!(
            std::fs::symlink_metadata(&valid_link).is_ok(),
            "valid link is preserved"
        );
        assert!(keeper.exists(), "real files are untouched");
    }

    #[test]
    fn clean_tree_removes_nothing() {
        let root = tempdir().unwrap();
        std::fs::create_dir_all(root.path().join("a/b")).unwrap();
        std::fs::write(root.path().join("a/b/f.txt"), "x").unwrap();
        assert_eq!(prune_dangling_symlinks(root.path()).unwrap(), 0);
    }

    /// A valid symlink *to a directory* is treated as a leaf and never followed.
    /// The link here points back at the walk root, so following it would recurse
    /// forever; terminating (and leaving the link in place) proves it is not
    /// followed — the same property that keeps pnpm's symlink graph cycle-free.
    #[test]
    fn does_not_follow_valid_directory_symlink() {
        let root = tempdir().unwrap();
        let base = root.path();

        std::fs::write(base.join("server.js"), "// server").unwrap();
        // A valid directory symlink that points back at the root: following it
        // would loop. `read_dir` reports it as a symlink, so the leaf branch
        // keeps it without descending.
        let dir_link = base.join("cycle");
        symlink(".", &dir_link).unwrap();

        let removed = prune_dangling_symlinks(base).unwrap();

        assert_eq!(removed, 0, "no dangling links, nothing removed");
        assert!(
            std::fs::symlink_metadata(&dir_link).is_ok(),
            "the valid directory symlink itself is preserved"
        );
    }

    /// The walk root being a dangling symlink is handled by the top-level branch:
    /// it is removed and counted.
    #[test]
    fn dangling_symlink_at_root_is_removed() {
        let root = tempdir().unwrap();
        let link = root.path().join("root_link");
        symlink("./missing_target", &link).unwrap();

        assert_eq!(prune_dangling_symlinks(&link).unwrap(), 1);
        assert!(
            std::fs::symlink_metadata(&link).is_err(),
            "the dangling root symlink is gone"
        );
    }

    #[test]
    fn restart_stanza_defaults_to_pm2() {
        for pm in [None, Some(""), Some("pm2"), Some("PM2"), Some(" pm2 ")] {
            let s = restart_stanza(pm, 3025).expect("pm2 selector is valid");
            assert!(s.contains("pm2 start"), "pm={pm:?} should use pm2");
            assert!(s.contains("PORT=3025"), "pm={pm:?} injects the port");
            assert!(!s.contains("systemctl"), "pm={pm:?} must not touch systemd");
        }
    }

    /// An unrecognized supervisor must abort the deploy, not quietly run pm2
    /// alongside a systemd-owned process and fight over the port.
    #[test]
    fn restart_stanza_rejects_unknown_process_manager() {
        for pm in ["system", "systemctl", "supervisord", "PM3"] {
            let err = restart_stanza(Some(pm), 3025)
                .expect_err("unknown process_manager must be rejected");
            let msg = err.to_string();
            assert!(msg.contains(pm), "error names the offending value: {msg}");
            assert!(msg.contains("systemd"), "error lists valid options: {msg}");
        }
    }

    #[test]
    fn restart_stanza_systemd_uses_user_unit_no_sudo() {
        let s = restart_stanza(Some("systemd"), 3025).expect("systemd selector is valid");
        assert!(s.contains("systemctl --user restart \"$UNIT\""));
        assert!(s.contains("UNIT=\"$PM2_APP.service\""));
        assert!(s.contains("XDG_RUNTIME_DIR=\"/run/user/$(id -u)\""));
        // No sudo (git drives its own user manager) and no pm2 fallback.
        assert!(!s.contains("sudo"), "must not require sudo");
        assert!(!s.contains("pm2 "), "systemd path must not call pm2");
        // Case-insensitive selector.
        assert_eq!(s, restart_stanza(Some("SystemD"), 3025).unwrap());
    }

    // ── Ecosystem env merge ──────────────────────────────────────────────────
    //
    // These run the generated shell under real bash and node, since the point
    // is what lands in the file on the host.

    const HAND_FILE: &str = r#"module.exports = {
  apps: [
    { name: "web", script: "server.js", cwd: "/srv/web",
      env_production: { NODE_ENV: "production", PORT: 3026, HAND_KEPT: "mine", OLD: "x" } },
    { name: "other", script: "o.js", env_production: { UNTOUCHED: "1" } },
  ],
};
"#;

    fn have_bash_and_node() -> bool {
        ["bash", "node"].iter().all(|bin| {
            Command::new(bin)
                .arg("--version")
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        })
    }

    fn vars(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect()
    }

    /// Runs the snippet in `dir` the way the deploy does, with PM2_APP set.
    fn run_merge(dir: &Path, env: Option<&HashMap<String, Value>>) -> std::process::Output {
        let script = format!(
            "set -e\nPM2_APP=\"web\"\n{}",
            ecosystem_env_merge_snippet(env)
        );
        Command::new("bash")
            .arg("-c")
            .arg(script)
            .current_dir(dir)
            .output()
            .unwrap()
    }

    /// The env_production of an app, as the host's pm2 would load it.
    fn env_of(dir: &Path, app: &str) -> Value {
        let out = Command::new("node")
            .arg("-e")
            .arg(format!(
                "var c=require('./ecosystem.config.cjs');\
                 console.log(JSON.stringify(c.apps.find(a=>a.name==='{app}').env_production))"
            ))
            .current_dir(dir)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        serde_json::from_slice(&out.stdout).unwrap()
    }

    /// Like `env_of`, for a file that exports a bare array of apps.
    fn env_of_array(dir: &Path, app: &str) -> Value {
        let out = Command::new("node")
            .arg("-e")
            .arg(format!(
                "var c=require('./ecosystem.config.cjs');\
                 console.log(JSON.stringify(c.find(a=>a.name==='{app}').env_production))"
            ))
            .current_dir(dir)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        serde_json::from_slice(&out.stdout).unwrap()
    }

    #[test]
    fn env_merge_sets_keys_and_keeps_hand_maintained_ones() {
        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();

        let env = vars(&[("STRIPE_WEBHOOK_SECRET", json!("whsec_1")), ("N", json!(5))]);
        let out = run_merge(dir.path(), Some(&env));
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );

        let web = env_of(dir.path(), "web");
        assert_eq!(web["STRIPE_WEBHOOK_SECRET"], "whsec_1");
        assert_eq!(web["N"], "5");
        assert_eq!(web["HAND_KEPT"], "mine");
        assert_eq!(web["PORT"], 3026);
        assert_eq!(env_of(dir.path(), "other"), json!({"UNTOUCHED": "1"}));

        let sidecar = std::fs::read_to_string(dir.path().join(".smbcloud-env-keys.json")).unwrap();
        assert_eq!(
            serde_json::from_str::<Value>(&sidecar).unwrap(),
            json!(["N", "STRIPE_WEBHOOK_SECRET"])
        );
        assert!(!sidecar.contains("whsec_1"), "the sidecar holds names only");
        assert!(dir
            .path()
            .join("ecosystem.config.cjs.smbcloud.bak")
            .exists());
    }

    #[test]
    fn env_merge_removes_keys_deleted_since_last_deploy_but_not_hand_kept_ones() {
        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();

        let first = vars(&[("A", json!("1")), ("B", json!("2"))]);
        assert!(run_merge(dir.path(), Some(&first)).status.success());
        let second = vars(&[("A", json!("1"))]);
        assert!(run_merge(dir.path(), Some(&second)).status.success());

        let web = env_of(dir.path(), "web");
        assert_eq!(web["A"], "1");
        assert!(web.get("B").is_none(), "B was managed and is now deleted");
        assert_eq!(web["HAND_KEPT"], "mine");
        assert_eq!(web["OLD"], "x");

        // Deleting the last key still cleans up, via the empty-map path.
        let empty = vars(&[]);
        assert!(run_merge(dir.path(), Some(&empty)).status.success());
        assert!(env_of(dir.path(), "web").get("A").is_none());
        assert_eq!(env_of(dir.path(), "web")["HAND_KEPT"], "mine");
    }

    #[test]
    fn env_merge_is_a_no_op_without_a_map_or_a_previous_sidecar() {
        assert_eq!(ecosystem_env_merge_snippet(None), "");

        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();
        assert!(run_merge(dir.path(), Some(&vars(&[]))).status.success());
        assert_eq!(
            std::fs::read_to_string(dir.path().join("ecosystem.config.cjs")).unwrap(),
            HAND_FILE
        );
        assert!(!dir.path().join(".smbcloud-env-keys.json").exists());
    }

    #[test]
    fn env_merge_carries_quotes_newlines_and_dollars_verbatim() {
        if !have_bash_and_node() {
            return;
        }
        let nasty = "a'b\"c\nline2 $HOME `id` $(whoami) \\n end";
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();

        let env = vars(&[
            ("NASTY", json!(nasty)),
            ("PEM", json!("-----BEGIN-----\nabc\n-----END-----")),
        ]);
        let out = run_merge(dir.path(), Some(&env));
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );

        let web = env_of(dir.path(), "web");
        assert_eq!(web["NASTY"], nasty);
        assert_eq!(web["PEM"], "-----BEGIN-----\nabc\n-----END-----");
    }

    #[test]
    fn env_merge_never_overrides_the_deploy_owned_keys() {
        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();

        let env = vars(&[
            ("PORT", json!("1")),
            ("NODE_ENV", json!("dev")),
            ("K", json!("v")),
        ]);
        assert!(run_merge(dir.path(), Some(&env)).status.success());

        let web = env_of(dir.path(), "web");
        assert_eq!(web["PORT"], 3026);
        assert_eq!(web["NODE_ENV"], "production");
        assert_eq!(web["K"], "v");
    }

    #[test]
    fn env_merge_handles_an_array_form_ecosystem_file() {
        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("ecosystem.config.cjs"),
            "module.exports = [{ name: 'web', script: 'server.js', env_production: { HAND_KEPT: 'mine' } }];\n",
        )
        .unwrap();

        let out = run_merge(dir.path(), Some(&vars(&[("K", json!("v"))])));
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );

        let web = env_of_array(dir.path(), "web");
        assert_eq!(web["K"], "v");
        assert_eq!(web["HAND_KEPT"], "mine");
    }

    #[test]
    fn env_merge_removes_a_managed_key_named_like_an_object_property() {
        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(dir.path().join("ecosystem.config.cjs"), HAND_FILE).unwrap();

        let first = vars(&[("constructor", json!("x")), ("toString", json!("y"))]);
        assert!(run_merge(dir.path(), Some(&first)).status.success());
        assert_eq!(env_of(dir.path(), "web")["constructor"], "x");

        let second = vars(&[("K", json!("v"))]);
        assert!(run_merge(dir.path(), Some(&second)).status.success());
        let web = env_of(dir.path(), "web");
        assert!(!web.as_object().unwrap().contains_key("constructor"));
        assert!(!web.as_object().unwrap().contains_key("toString"));
        assert_eq!(web["K"], "v");
    }

    #[test]
    fn env_merge_fails_loudly_when_the_app_is_not_in_the_file() {
        if !have_bash_and_node() {
            return;
        }
        let dir = tempdir().unwrap();
        std::fs::write(
            dir.path().join("ecosystem.config.cjs"),
            "module.exports = { apps: [{ name: 'else' }] };\n",
        )
        .unwrap();

        let out = run_merge(dir.path(), Some(&vars(&[("K", json!("v"))])));
        assert!(!out.status.success());
        assert!(String::from_utf8_lossy(&out.stderr).contains("no app named web"));
    }
}