offline-rn-shell 0.4.0

React Native android/ios shell cache and mesh native setup for Offline CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
//! Copy React Native `android/` + `ios/` shells after scaffold.
//!
//! Shells are cached under `~/.offline/cache/` by RN version; module identity
//! is rewritten when applying to a project.

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

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

/// Env var override for `~/.offline` (matches offline-cli config dir).
const ENV_CONFIG_DIR: &str = "OFFLINE_CONFIG_DIR";

fn offline_config_dir() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os(ENV_CONFIG_DIR) {
        return Ok(PathBuf::from(dir));
    }
    let home = dirs::home_dir().context("could not determine home directory")?;
    Ok(home.join(".offline"))
}

/// React Native version pinned in our starter templates' package.json.
const RN_VERSION: &str = "0.85.2";

/// Fixed module name used inside the on-disk shell cache. Rewritten to the
/// project module name when copying into a target app.
const CACHE_MODULE: &str = "OfflineShell";

/// Convert a slug like `my-offline-app` → `MyOfflineApp` for RN native module names.
pub fn rn_module_name(slug: &str) -> String {
    slug.split('-')
        .filter(|part| !part.is_empty())
        .map(capitalize_ascii)
        .collect()
}

fn capitalize_ascii(part: &str) -> String {
    let mut chars = part.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
    }
}

fn rn_shell_cache_dir() -> Result<PathBuf> {
    Ok(offline_config_dir()?
        .join("cache")
        .join(format!("rn-shell-{RN_VERSION}")))
}

fn shell_cache_ready(cache: &Path) -> bool {
    cache.join(".ready").is_file() && cache.join("android").is_dir() && cache.join("ios").is_dir()
}

/// `@react-native-community/cli` version that React Native 0.85.2's own
/// template (`@react-native-community/template@0.85.2`) depends on. Pinned so
/// the shell generation is reproducible instead of following npm `latest`.
const RN_COMMUNITY_CLI_VERSION: &str = "20.1.0";

/// Env var naming a prebuilt shell tarball (`android/`, `ios/`, optional
/// `Gemfile` at the archive root) to use instead of running `init`.
const ENV_SHELL_URL: &str = "OFFLINE_RN_SHELL_URL";

/// Ensure a cached RN shell exists.
///
/// No prebuilt shell is published: the CLI repository is internal and its
/// releases carry no shell tarball, so a default download URL would only
/// 404. The shell is therefore generated deliberately with
/// `npx @react-native-community/cli@<pinned> init --version <RN_VERSION>` on a
/// cache miss. Set `OFFLINE_RN_SHELL_URL` to use a prebuilt tarball (for
/// example an internal mirror); if that download fails, `init` still runs.
fn ensure_shell_cache() -> Result<PathBuf> {
    let cache = rn_shell_cache_dir()?;
    if shell_cache_ready(&cache) {
        return Ok(cache);
    }

    // Drop a partial cache before regenerating.
    if cache.exists() {
        let _ = std::fs::remove_dir_all(&cache);
    }

    if let Some(url) = rn_shell_download_url() {
        if try_download_shell_cache(&url, &cache).is_ok() && shell_cache_ready(&cache) {
            return Ok(cache);
        }
        let _ = std::fs::remove_dir_all(&cache);
    }

    populate_shell_cache_via_npx(&cache)
}

fn rn_shell_download_url() -> Option<String> {
    std::env::var(ENV_SHELL_URL)
        .ok()
        .map(|u| u.trim().to_string())
        .filter(|u| !u.is_empty())
}

fn try_download_shell_cache(url: &str, cache: &Path) -> Result<()> {
    let agent = ureq::Agent::new_with_config(
        ureq::Agent::config_builder()
            .timeout_global(Some(std::time::Duration::from_secs(120)))
            .user_agent(concat!("offline-cli/", env!("CARGO_PKG_VERSION")))
            .build(),
    );
    let response = agent
        .get(url)
        .call()
        .map_err(|e| anyhow::anyhow!("download RN shell from {url}: {e}"))?;

    let tmp_tar = std::env::temp_dir().join(format!(
        "offline-rn-shell-{}-{}.tar.gz",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    ));
    let mut file = std::fs::File::create(&tmp_tar)
        .with_context(|| format!("create temp archive at {}", tmp_tar.display()))?;
    std::io::copy(&mut response.into_body().into_reader(), &mut file)
        .context("write downloaded RN shell archive")?;
    drop(file);

    std::fs::create_dir_all(cache)
        .with_context(|| format!("create shell cache at {}", cache.display()))?;

    let tar_gz = std::fs::File::open(&tmp_tar).context("reopen downloaded RN shell archive")?;
    let decoder = flate2::read::GzDecoder::new(tar_gz);
    let mut archive = tar::Archive::new(decoder);
    archive.unpack(cache).context("extract RN shell archive")?;
    let _ = std::fs::remove_file(&tmp_tar);

    if !cache.join(".ready").is_file() {
        std::fs::write(cache.join(".ready"), RN_VERSION.as_bytes())
            .with_context(|| format!("write {}", cache.join(".ready").display()))?;
    }
    Ok(())
}

fn populate_shell_cache_via_npx(cache: &Path) -> Result<PathBuf> {
    let tmp_base = std::env::temp_dir().join(format!(
        "offline-rn-init-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    ));
    std::fs::create_dir_all(&tmp_base).with_context(|| {
        format!(
            "create temp dir for react-native init at {}",
            tmp_base.display()
        )
    })?;

    let init_result = (|| -> Result<()> {
        let cli = format!("@react-native-community/cli@{RN_COMMUNITY_CLI_VERSION}");
        let output = Command::new("npx")
            .args([
                "--yes",
                cli.as_str(),
                "init",
                CACHE_MODULE,
                "--version",
                RN_VERSION,
                "--skip-install",
                "--pm",
                "npm",
            ])
            .current_dir(&tmp_base)
            .output()
            .with_context(|| format!("failed to spawn `npx {cli} init` (is Node.js installed?)"))?;

        if !output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            bail!(
                "react-native init exited with {}:\n{stdout}{stderr}",
                output.status
            );
        }

        let shell_root = tmp_base.join(CACHE_MODULE);
        std::fs::create_dir_all(cache)
            .with_context(|| format!("create shell cache at {}", cache.display()))?;
        copy_dir_all(&shell_root.join("android"), &cache.join("android"))
            .context("cache android/")?;
        copy_dir_all(&shell_root.join("ios"), &cache.join("ios")).context("cache ios/")?;
        copy_file_if_missing(&shell_root.join("Gemfile"), &cache.join("Gemfile"))?;
        // Marker written last so a partial cache is never treated as ready.
        std::fs::write(cache.join(".ready"), RN_VERSION.as_bytes())
            .with_context(|| format!("write {}", cache.join(".ready").display()))?;
        Ok(())
    })();

    let _ = std::fs::remove_dir_all(&tmp_base);
    if let Err(err) = init_result {
        let _ = std::fs::remove_dir_all(cache);
        return Err(err);
    }
    Ok(cache.to_path_buf())
}

fn apply_shell_from_cache(cache: &Path, target_dir: &Path, module_name: &str) -> Result<()> {
    copy_dir_all(&cache.join("android"), &target_dir.join("android")).context("copy android/")?;
    copy_dir_all(&cache.join("ios"), &target_dir.join("ios")).context("copy ios/")?;
    copy_file_if_missing(&cache.join("Gemfile"), &target_dir.join("Gemfile"))?;
    copy_file_if_missing(
        &cache.join("ios").join(".xcode.env"),
        &target_dir.join("ios").join(".xcode.env"),
    )?;
    if module_name != CACHE_MODULE {
        rewrite_shell_identity(target_dir, module_name)?;
    }
    Ok(())
}

/// Rename path segments and rewrite text contents from `CACHE_MODULE` → `module_name`.
fn rewrite_shell_identity(root: &Path, module_name: &str) -> Result<()> {
    let from = CACHE_MODULE;
    let to = module_name;
    let from_lower = from.to_ascii_lowercase();
    let to_lower = to.to_ascii_lowercase();
    let from_pkg = format!("com.{from_lower}");
    let to_pkg = format!("com.{to_lower}");

    rename_path_components(root, from, to)?;
    if from_lower != from {
        rename_path_components(root, &from_lower, &to_lower)?;
    }

    replace_in_text_files(
        root,
        &[
            (from_pkg.as_str(), to_pkg.as_str()),
            (from, to),
            (from_lower.as_str(), to_lower.as_str()),
        ],
    )?;
    Ok(())
}

fn rename_path_components(root: &Path, from: &str, to: &str) -> Result<()> {
    let mut paths = Vec::new();
    collect_paths(root, &mut paths)?;
    // Deepest paths first so parents rename after children.
    paths.sort_by_key(|p| std::cmp::Reverse(p.components().count()));
    for path in paths {
        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
            continue;
        };
        if !name.contains(from) {
            continue;
        }
        let new_name = name.replace(from, to);
        let dest = path.with_file_name(new_name);
        if dest != path {
            std::fs::rename(&path, &dest)
                .with_context(|| format!("rename {} → {}", path.display(), dest.display()))?;
        }
    }
    Ok(())
}

fn collect_paths(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_paths(&path, out)?;
        }
        out.push(path);
    }
    Ok(())
}

fn replace_in_text_files(root: &Path, replacements: &[(&str, &str)]) -> Result<()> {
    let mut files = Vec::new();
    collect_files(root, &mut files)?;
    for path in files {
        let Ok(bytes) = std::fs::read(&path) else {
            continue;
        };
        let Ok(mut content) = String::from_utf8(bytes) else {
            continue;
        };
        let mut changed = false;
        for (from, to) in replacements {
            if content.contains(from) {
                content = content.replace(from, to);
                changed = true;
            }
        }
        if changed {
            std::fs::write(&path, content)
                .with_context(|| format!("rewrite {}", path.display()))?;
        }
    }
    Ok(())
}

fn collect_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_files(&path, out)?;
        } else {
            out.push(path);
        }
    }
    Ok(())
}

/// Copy cached (or freshly generated) `android/` + `ios/` shells into `target_dir`.
pub fn add_native_shells(target_dir: &Path, module_name: &str) -> Result<()> {
    if target_dir.join("android").is_dir() && target_dir.join("ios").is_dir() {
        return Ok(());
    }

    let cache = ensure_shell_cache()?;
    apply_shell_from_cache(&cache, target_dir, module_name)
}

/// Result of post-scaffold React Native native setup.
#[derive(Debug, Default)]
pub struct ReactNativeFinalizeResult {
    pub native_shells_added: bool,
    pub extra_files: Vec<String>,
    pub warnings: Vec<String>,
}

/// After JS/TS template generation: add native shells and mesh-related native config.
pub fn finalize_react_native_mesh_app(
    target_dir: &Path,
    module_name: &str,
    mesh_enabled: bool,
) -> ReactNativeFinalizeResult {
    let mut result = ReactNativeFinalizeResult::default();

    match add_native_shells(target_dir, module_name) {
        Ok(()) => {
            result.native_shells_added =
                target_dir.join("android").is_dir() && target_dir.join("ios").is_dir();
            if result.native_shells_added {
                result.extra_files.push("android/".to_string());
                result.extra_files.push("ios/".to_string());
            }
        }
        Err(err) => result
            .warnings
            .push(format!("Native android/ios shells not added: {err:#}")),
    }

    if target_dir.join("android").is_dir() {
        if let Err(err) = patch_network_binding(target_dir, module_name) {
            result.warnings.push(format!(
                "Android Wi‑Fi network binding not applied: {err:#}"
            ));
        }
    }

    if mesh_enabled && target_dir.join("ios").is_dir() {
        if let Err(err) = patch_mesh_native_permissions(target_dir, module_name) {
            result
                .warnings
                .push(format!("Mesh native permissions/pod not applied: {err:#}"));
        }
    }

    if uses_offline_id(target_dir) && target_dir.join("ios").is_dir() {
        match patch_app_attest_entitlement(target_dir, module_name) {
            Ok(true) => result
                .extra_files
                .push(format!("ios/{module_name}/{module_name}.entitlements")),
            Ok(false) => {}
            Err(err) => result.warnings.push(format!(
                "App Attest entitlement not added (add the App Attest capability in Xcode): {err:#}"
            )),
        }
    }

    result
}

/// The app depends on `@offline-protocol/id-react-native`, whose sign-ins
/// carry an App Attest proof on iOS.
fn uses_offline_id(target_dir: &Path) -> bool {
    std::fs::read_to_string(target_dir.join("package.json"))
        .map(|pkg| pkg.contains("\"@offline-protocol/id-react-native\""))
        .unwrap_or(false)
}

/// The App Attest environment entitlement. `production` makes every build,
/// including one run from Xcode, attest in Apple's production environment,
/// which auth-service accepts without `offline apps native dev-builds on`.
pub const APP_ATTEST_ENTITLEMENT: &str = "com.apple.developer.devicecheck.appattest-environment";

const APP_ATTEST_ENTITLEMENTS_PLIST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.developer.devicecheck.appattest-environment</key>
	<string>production</string>
</dict>
</plist>
"#;

/// Give the iOS app target the App Attest entitlement: write
/// `ios/<Module>/<Module>.entitlements` and point the target's
/// `CODE_SIGN_ENTITLEMENTS` at it (Debug and Release). Idempotent; an
/// existing entitlements setting is left alone. Returns whether the
/// entitlements file was written.
pub fn patch_app_attest_entitlement(target_dir: &Path, module_name: &str) -> Result<bool> {
    let pbxproj = target_dir.join(format!("ios/{module_name}.xcodeproj/project.pbxproj"));
    if !pbxproj.is_file() {
        bail!("{} not found", pbxproj.display());
    }
    let content =
        std::fs::read_to_string(&pbxproj).with_context(|| format!("read {}", pbxproj.display()))?;
    if content.contains("CODE_SIGN_ENTITLEMENTS") {
        return Ok(false);
    }
    let info_plist = format!("INFOPLIST_FILE = {module_name}/Info.plist;");
    let setting = format!("CODE_SIGN_ENTITLEMENTS = {module_name}/{module_name}.entitlements;");
    let mut patched = String::with_capacity(content.len() + 256);
    let mut count = 0;
    for line in content.split_inclusive('\n') {
        if line.trim() == info_plist {
            let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
            patched.push_str(&indent);
            patched.push_str(&setting);
            patched.push('\n');
            count += 1;
        }
        patched.push_str(line);
    }
    if count == 0 {
        bail!(
            "no build configuration with `{info_plist}` in {}",
            pbxproj.display()
        );
    }
    let entitlements = target_dir.join(format!("ios/{module_name}/{module_name}.entitlements"));
    let written = !entitlements.exists();
    if written {
        std::fs::write(&entitlements, APP_ATTEST_ENTITLEMENTS_PLIST)
            .with_context(|| format!("write {}", entitlements.display()))?;
    }
    std::fs::write(&pbxproj, patched).with_context(|| format!("write {}", pbxproj.display()))?;
    Ok(written)
}

/// Add Android/iOS permissions and iOS Podfile cleanup required by mesh-sdk.
pub fn patch_mesh_native_permissions(target_dir: &Path, module_name: &str) -> Result<()> {
    let podfile = target_dir.join("ios/Podfile");
    if podfile.is_file() {
        patch_mesh_ios_podfile(&podfile)?;
        patch_mesh_ios_podfile_build_settings(&podfile)?;
    }
    let manifest = target_dir.join("android/app/src/main/AndroidManifest.xml");
    if manifest.is_file() {
        patch_android_mesh_permissions(&manifest)?;
    }
    let plist = target_dir.join(format!("ios/{module_name}/Info.plist"));
    if plist.is_file() {
        patch_ios_mesh_permissions(&plist)?;
    }
    Ok(())
}

/// Add Android NetworkBinding for unvalidated Wi‑Fi uplinks.
pub fn patch_network_binding(target_dir: &Path, module_name: &str) -> Result<()> {
    let package = format!("com.{}", module_name.to_ascii_lowercase());
    let java_root = target_dir
        .join("android/app/src/main/java")
        .join(package.replace('.', "/"));
    if !java_root.is_dir() {
        // Default package path missing; scan the java tree.
        return patch_network_binding_in_java_tree(target_dir, module_name);
    }
    write_network_binding_sources(&java_root, &package)?;
    patch_main_application_for_network_binding(&java_root)?;
    let manifest = target_dir.join("android/app/src/main/AndroidManifest.xml");
    if manifest.is_file() {
        patch_android_network_binding_permissions(&manifest)?;
    }
    Ok(())
}

fn patch_network_binding_in_java_tree(target_dir: &Path, module_name: &str) -> Result<()> {
    let java_base = target_dir.join("android/app/src/main/java");
    if !java_base.is_dir() {
        return Ok(());
    }
    let main_app = find_file_named(&java_base, "MainApplication.kt")
        .or_else(|| find_file_named(&java_base, "MainApplication.java"));
    let Some(main_app) = main_app else {
        return Ok(());
    };
    let java_root = main_app.parent().unwrap().to_path_buf();
    let package = package_from_java_root(&java_base, &java_root)
        .unwrap_or_else(|| format!("com.{}", module_name.to_ascii_lowercase()));
    write_network_binding_sources(&java_root, &package)?;
    patch_main_application_for_network_binding(&java_root)?;
    let manifest = target_dir.join("android/app/src/main/AndroidManifest.xml");
    if manifest.is_file() {
        patch_android_network_binding_permissions(&manifest)?;
    }
    Ok(())
}

fn find_file_named(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
    let mut stack = vec![dir.to_path_buf()];
    while let Some(cur) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&cur) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else if entry.file_name() == name {
                return Some(path);
            }
        }
    }
    None
}

fn package_from_java_root(java_base: &Path, java_root: &Path) -> Option<String> {
    let rel = java_root.strip_prefix(java_base).ok()?;
    let parts: Vec<_> = rel
        .components()
        .filter_map(|c| match c {
            std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect();
    if parts.is_empty() {
        None
    } else {
        Some(parts.join("."))
    }
}

fn write_network_binding_sources(java_root: &Path, package: &str) -> Result<()> {
    let module_path = java_root.join("NetworkBindingModule.kt");
    let package_path = java_root.join("NetworkBindingPackage.kt");
    if !module_path.exists() {
        std::fs::write(&module_path, network_binding_module_kt(package))
            .with_context(|| format!("write {}", module_path.display()))?;
    }
    if !package_path.exists() {
        std::fs::write(&package_path, network_binding_package_kt(package))
            .with_context(|| format!("write {}", package_path.display()))?;
    }
    Ok(())
}

fn patch_main_application_for_network_binding(java_root: &Path) -> Result<()> {
    let kt = java_root.join("MainApplication.kt");
    if kt.is_file() {
        let mut content =
            std::fs::read_to_string(&kt).with_context(|| format!("read {}", kt.display()))?;
        if content.contains("NetworkBindingPackage") {
            return Ok(());
        }
        let needle = "PackageList(this).packages.apply {";
        let Some(idx) = content.find(needle) else {
            bail!("MainApplication.kt missing PackageList apply block");
        };
        let insert_at = idx + needle.len();
        content.insert_str(
            insert_at,
            "\n          // Bind Offline ID HTTPS to Wi‑Fi even when Android marks it unvalidated.\n          add(NetworkBindingPackage())",
        );
        std::fs::write(&kt, content).with_context(|| format!("write {}", kt.display()))?;
        return Ok(());
    }
    Ok(())
}

fn patch_android_network_binding_permissions(path: &Path) -> Result<()> {
    let mut content =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    let mut changed = false;
    for perm in [
        "android.permission.ACCESS_NETWORK_STATE",
        "android.permission.CHANGE_NETWORK_STATE",
    ] {
        if content.contains(perm) {
            continue;
        }
        let line = format!("    <uses-permission android:name=\"{perm}\" />\n");
        if let Some(idx) =
            content.find("<uses-permission android:name=\"android.permission.INTERNET\" />")
        {
            let end = content[idx..]
                .find('\n')
                .map(|i| idx + i + 1)
                .unwrap_or(content.len());
            content.insert_str(end, &line);
            changed = true;
        } else if let Some(idx) = content.find("<application") {
            content.insert_str(idx, &line);
            changed = true;
        }
    }
    if changed {
        std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
    }
    Ok(())
}

fn network_binding_module_kt(package: &str) -> String {
    format!(
        r#"package {package}

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.os.Handler
import android.os.Looper
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import java.util.concurrent.atomic.AtomicBoolean

/** Prefer VALIDATED Wi‑Fi, else cellular; avoid unvalidated Wi‑Fi. */
class NetworkBindingModule(
  private val reactContext: ReactApplicationContext,
) : ReactContextBaseJavaModule(reactContext) {{

  private val mainHandler = Handler(Looper.getMainLooper())
  @Volatile private var pendingCallback: ConnectivityManager.NetworkCallback? = null

  override fun getName(): String = NAME

  @ReactMethod
  fun preferWifi(promise: Promise) {{
    preferUplink(promise)
  }}

  @ReactMethod
  fun preferUplink(promise: Promise) {{
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {{
      promise.resolve(false)
      return
    }}

    val cm =
      reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
    if (cm == null) {{
      promise.resolve(false)
      return
    }}

    val existing = findValidatedUplink(cm)
    if (existing != null && bindTo(cm, existing)) {{
      promise.resolve(true)
      return
    }}

    requestValidatedInternet(cm, promise)
  }}

  @ReactMethod
  fun clearBinding(promise: Promise) {{
    val cm =
      reactContext.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
    if (cm == null) {{
      promise.resolve(false)
      return
    }}
    unregisterPending(cm)
    val cleared =
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
        cm.bindProcessToNetwork(null)
      }} else {{
        @Suppress("DEPRECATION")
        ConnectivityManager.setProcessDefaultNetwork(null)
      }}
    promise.resolve(cleared)
  }}

  private fun isValidated(caps: NetworkCapabilities): Boolean {{
    if (!caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {{
      return false
    }}
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
      caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
    }} else {{
      true
    }}
  }}

  private fun findValidatedUplink(cm: ConnectivityManager): Network? {{
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return null

    var validatedWifi: Network? = null
    var validatedOther: Network? = null

    for (network in cm.allNetworks) {{
      val caps = cm.getNetworkCapabilities(network) ?: continue
      if (!isValidated(caps)) continue
      if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {{
        validatedWifi = network
      }} else {{
        validatedOther = network
      }}
    }}

    return validatedWifi ?: validatedOther
  }}

  private fun requestValidatedInternet(cm: ConnectivityManager, promise: Promise) {{
    val settled = AtomicBoolean(false)
    fun settle(ok: Boolean) {{
      if (settled.compareAndSet(false, true)) {{
        promise.resolve(ok)
      }}
    }}

    val builder =
      NetworkRequest.Builder()
        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
      builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
    }}
    val request = builder.build()

    val callback =
      object : ConnectivityManager.NetworkCallback() {{
        override fun onAvailable(network: Network) {{
          tryBindValidated(cm, network, settled, promise)
        }}

        override fun onCapabilitiesChanged(
          network: Network,
          networkCapabilities: NetworkCapabilities,
        ) {{
          if (isValidated(networkCapabilities)) {{
            tryBindValidated(cm, network, settled, promise)
          }}
        }}

        override fun onUnavailable() {{
          mainHandler.post {{
            unregisterPending(cm)
            settle(false)
          }}
        }}
      }}

    pendingCallback = callback
    try {{
      cm.requestNetwork(request, callback)
    }} catch (_: SecurityException) {{
      pendingCallback = null
      settle(false)
      return
    }} catch (_: RuntimeException) {{
      pendingCallback = null
      settle(false)
      return
    }}

    mainHandler.postDelayed(
      {{
        if (settled.get()) return@postDelayed
        unregisterPending(cm)
        val network = findValidatedUplink(cm)
        settle(network != null && bindTo(cm, network))
      }},
      REQUEST_TIMEOUT_MS,
    )
  }}

  private fun tryBindValidated(
    cm: ConnectivityManager,
    network: Network,
    settled: AtomicBoolean,
    promise: Promise,
  ) {{
    mainHandler.post {{
      if (settled.get()) return@post
      val caps = cm.getNetworkCapabilities(network)
      if (caps == null || !isValidated(caps)) return@post
      val ok = bindTo(cm, network)
      unregisterPending(cm)
      if (settled.compareAndSet(false, true)) {{
        promise.resolve(ok)
      }}
    }}
  }}

  private fun bindTo(cm: ConnectivityManager, network: Network): Boolean {{
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {{
      cm.bindProcessToNetwork(network)
    }} else {{
      @Suppress("DEPRECATION")
      ConnectivityManager.setProcessDefaultNetwork(network)
    }}
  }}

  private fun unregisterPending(cm: ConnectivityManager) {{
    val callback = pendingCallback ?: return
    pendingCallback = null
    try {{
      cm.unregisterNetworkCallback(callback)
    }} catch (_: IllegalArgumentException) {{
      // Already unregistered.
    }}
  }}

  companion object {{
    const val NAME = "NetworkBinding"
    private const val REQUEST_TIMEOUT_MS = 6_000L
  }}
}}
"#
    )
}

fn network_binding_package_kt(package: &str) -> String {
    format!(
        r#"package {package}

import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager

class NetworkBindingPackage : ReactPackage {{
  override fun createNativeModules(
    reactContext: ReactApplicationContext,
  ): List<NativeModule> = listOf(NetworkBindingModule(reactContext))

  override fun createViewManagers(
    reactContext: ReactApplicationContext,
  ): List<ViewManager<*, *>> = emptyList()
}}
"#
    )
}

fn patch_android_mesh_permissions(path: &Path) -> Result<()> {
    let mut content =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    if content.contains("BLUETOOTH_SCAN") {
        return Ok(());
    }
    const PERMS: &str = r#"
    <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
    <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.NEARBY_WIFI_DEVICES" android:usesPermissionFlags="neverForLocation" />
"#;
    let marker = "<application";
    let Some(idx) = content.find(marker) else {
        bail!("AndroidManifest.xml missing <application> tag");
    };
    content.insert_str(idx, PERMS);
    std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

fn patch_ios_mesh_permissions(path: &Path) -> Result<()> {
    let mut content =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    const PLIST_SNIPPETS: &[(&str, &str)] = &[
        (
            "NSBluetoothAlwaysUsageDescription",
            r#"
	<key>NSBluetoothAlwaysUsageDescription</key>
	<string>Find and message nearby people over the mesh.</string>"#,
        ),
        (
            "NSBluetoothPeripheralUsageDescription",
            r#"
	<key>NSBluetoothPeripheralUsageDescription</key>
	<string>Find and message nearby people over the mesh.</string>"#,
        ),
        (
            "NSLocationWhenInUseUsageDescription",
            r#"
	<key>NSLocationWhenInUseUsageDescription</key>
	<string>Location is used for Bluetooth peer discovery.</string>"#,
        ),
        (
            "UIBackgroundModes",
            r#"
	<key>UIBackgroundModes</key>
	<array>
		<string>bluetooth-central</string>
		<string>bluetooth-peripheral</string>
	</array>"#,
        ),
    ];
    let marker = "</dict>";
    let Some(mut idx) = content.rfind(marker) else {
        bail!("Info.plist missing closing </dict>");
    };
    for (key, snippet) in PLIST_SNIPPETS {
        if !content.contains(key) {
            content.insert_str(idx, snippet);
            idx += snippet.len();
        }
    }
    std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

/// Remove legacy manual MeshSdk pod lines; `@offline-protocol/mesh-sdk` autolinks via
/// `MeshSdk.podspec` at the package root (`use_native_modules!`).
fn patch_mesh_ios_podfile(path: &Path) -> Result<()> {
    let content =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    let mut lines: Vec<&str> = content.lines().collect();
    let before = lines.len();
    lines.retain(|line| !is_manual_mesh_sdk_pod_line(line));
    if lines.len() == before {
        return Ok(());
    }
    let mut patched = lines.join("\n");
    if content.ends_with('\n') {
        patched.push('\n');
    }
    std::fs::write(path, patched).with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

fn is_manual_mesh_sdk_pod_line(line: &str) -> bool {
    let trimmed = line.trim();
    trimmed.starts_with("pod 'MeshSdk'") || trimmed.starts_with("pod \"MeshSdk\"")
}

/// Xcode 26 / RN fmt and modular-include build fixes for mesh iOS shells.
fn patch_mesh_ios_podfile_build_settings(path: &Path) -> Result<()> {
    let mut content =
        std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
    if content.contains("FMT_USE_CONSTEVAL") {
        return Ok(());
    }
    const SNIPPET: &str = r##"
    # offline-rn-shell: fmt + modular includes for Xcode 26 / RN 0.82+
    fmt_base = File.join(installer.sandbox.root, 'fmt', 'include', 'fmt', 'base.h')
    if File.exist?(fmt_base)
      original = File.read(fmt_base)
      patched = original.gsub('#  define FMT_USE_CONSTEVAL 1',
                              '#  define FMT_USE_CONSTEVAL 0')
      if patched != original
        File.write(fmt_base, patched)
        Pod::UI.puts 'Patched fmt/base.h: forced FMT_USE_CONSTEVAL=0 (Xcode 26.5 / clang 21)'.yellow
      end
    end

    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |build_config|
        build_config.build_settings['CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES'] = 'YES'
        other_cflags = build_config.build_settings['OTHER_CFLAGS'] || '$(inherited)'
        other_cxxflags = build_config.build_settings['OTHER_CPLUSPLUSFLAGS'] || '$(inherited)'
        warning_flag = '-Wno-error=return-type'
        unless other_cflags.include?(warning_flag)
          build_config.build_settings['OTHER_CFLAGS'] = "#{other_cflags} #{warning_flag}"
        end
        unless other_cxxflags.include?(warning_flag)
          build_config.build_settings['OTHER_CPLUSPLUSFLAGS'] = "#{other_cxxflags} #{warning_flag}"
        end
        build_config.build_settings['SWIFT_STRICT_CONCURRENCY'] ||= 'minimal'
      end
    end
"##;
    let marker = "react_native_post_install(";
    let Some(start) = content.find(marker) else {
        return Ok(());
    };
    // Insert after the closing `)` of react_native_post_install(...) — typically the
    // line `    )` immediately following the call.
    let after_start = &content[start..];
    let Some(close_paren) = after_start.find("\n    )") else {
        return Ok(());
    };
    let insert_at = start + close_paren + "\n    )".len();
    content.insert_str(insert_at, SNIPPET);
    std::fs::write(path, content).with_context(|| format!("write {}", path.display()))?;
    Ok(())
}

fn copy_file_if_missing(from: &Path, to: &Path) -> Result<()> {
    if to.exists() || !from.is_file() {
        return Ok(());
    }
    if let Some(parent) = to.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::copy(from, to)?;
    Ok(())
}

fn copy_dir_all(from: &Path, to: &Path) -> Result<()> {
    if !from.is_dir() {
        bail!("expected directory at {}", from.display());
    }
    std::fs::create_dir_all(to)?;
    for entry in std::fs::read_dir(from)? {
        let entry = entry?;
        let dest = to.join(entry.file_name());
        if entry.file_type()?.is_dir() {
            copy_dir_all(&entry.path(), &dest)?;
        } else {
            std::fs::copy(entry.path(), dest)?;
        }
    }
    Ok(())
}

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

    #[test]
    fn app_attest_entitlement_is_added_to_both_configurations_once() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("ios/MyApp.xcodeproj")).unwrap();
        std::fs::create_dir_all(root.join("ios/MyApp")).unwrap();
        let pbxproj = root.join("ios/MyApp.xcodeproj/project.pbxproj");
        std::fs::write(
            &pbxproj,
            "\t\t\tbuildSettings = {\n\t\t\t\tENABLE_BITCODE = NO;\n\t\t\t\tINFOPLIST_FILE = MyApp/Info.plist;\n\t\t\t};\n\t\t\tbuildSettings = {\n\t\t\t\tINFOPLIST_FILE = MyApp/Info.plist;\n\t\t\t};\n",
        )
        .unwrap();
        assert!(patch_app_attest_entitlement(root, "MyApp").unwrap());
        let first = std::fs::read_to_string(&pbxproj).unwrap();
        assert_eq!(
            first
                .matches("\t\t\t\tCODE_SIGN_ENTITLEMENTS = MyApp/MyApp.entitlements;\n\t\t\t\tINFOPLIST_FILE")
                .count(),
            2
        );
        let plist = std::fs::read_to_string(root.join("ios/MyApp/MyApp.entitlements")).unwrap();
        assert!(plist.contains(APP_ATTEST_ENTITLEMENT));
        assert!(plist.contains("<string>production</string>"));
        assert!(!patch_app_attest_entitlement(root, "MyApp").unwrap());
        assert_eq!(std::fs::read_to_string(&pbxproj).unwrap(), first);
    }

    #[test]
    fn app_attest_entitlement_follows_offline_id() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"dependencies":{"react-native":"0.85.2"}}"#,
        )
        .unwrap();
        assert!(!uses_offline_id(tmp.path()));
        std::fs::write(
            tmp.path().join("package.json"),
            r#"{"dependencies":{"@offline-protocol/id-react-native":"^0.4.0"}}"#,
        )
        .unwrap();
        assert!(uses_offline_id(tmp.path()));
    }

    #[test]
    fn rn_module_name_pascal_cases_slug() {
        assert_eq!(rn_module_name("my-offline-app"), "MyOfflineApp");
        assert_eq!(rn_module_name("myapp"), "Myapp");
        assert_eq!(rn_module_name("my_app"), "My_app");
    }

    #[test]
    fn patch_android_mesh_permissions_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let manifest = tmp.path().join("AndroidManifest.xml");
        std::fs::write(
            &manifest,
            r#"<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:name=".MainApplication" />
</manifest>"#,
        )
        .unwrap();
        patch_android_mesh_permissions(&manifest).unwrap();
        let first = std::fs::read_to_string(&manifest).unwrap();
        assert!(first.contains("BLUETOOTH_SCAN"));
        patch_android_mesh_permissions(&manifest).unwrap();
        let second = std::fs::read_to_string(&manifest).unwrap();
        assert_eq!(
            first.matches("BLUETOOTH_SCAN").count(),
            second.matches("BLUETOOTH_SCAN").count()
        );
    }

    #[test]
    fn patch_android_network_binding_permissions_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let manifest = tmp.path().join("AndroidManifest.xml");
        std::fs::write(
            &manifest,
            r#"<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:name=".MainApplication" />
</manifest>"#,
        )
        .unwrap();
        patch_android_network_binding_permissions(&manifest).unwrap();
        let first = std::fs::read_to_string(&manifest).unwrap();
        assert!(first.contains("ACCESS_NETWORK_STATE"));
        assert!(first.contains("CHANGE_NETWORK_STATE"));
        patch_android_network_binding_permissions(&manifest).unwrap();
        let second = std::fs::read_to_string(&manifest).unwrap();
        assert_eq!(
            first.matches("ACCESS_NETWORK_STATE").count(),
            second.matches("ACCESS_NETWORK_STATE").count()
        );
    }

    #[test]
    fn patch_main_application_adds_network_binding_package() {
        let tmp = tempfile::tempdir().unwrap();
        let main = tmp.path().join("MainApplication.kt");
        std::fs::write(
            &main,
            r#"package com.example

class MainApplication {
  val packages =
    PackageList(this).packages.apply {
          // placeholder
        }
}
"#,
        )
        .unwrap();
        patch_main_application_for_network_binding(tmp.path()).unwrap();
        let content = std::fs::read_to_string(&main).unwrap();
        assert!(content.contains("add(NetworkBindingPackage())"));
        patch_main_application_for_network_binding(tmp.path()).unwrap();
        assert_eq!(content.matches("NetworkBindingPackage").count(), 1);
    }

    #[test]
    fn patch_mesh_ios_podfile_strips_legacy_manual_mesh_sdk_pod() {
        let tmp = tempfile::tempdir().unwrap();
        let podfile = tmp.path().join("Podfile");
        std::fs::write(
            &podfile,
            "target 'App' do\n  config = use_native_modules!\n  pod 'MeshSdk', :path => '../node_modules/@offline-protocol/mesh-sdk/ios'\n  use_react_native!\nend\n",
        )
        .unwrap();
        patch_mesh_ios_podfile(&podfile).unwrap();
        let content = std::fs::read_to_string(&podfile).unwrap();
        assert!(!content.contains("MeshSdk"));
        patch_mesh_ios_podfile(&podfile).unwrap();
        assert!(!content.contains("MeshSdk"));
    }

    #[test]
    fn patch_mesh_ios_podfile_build_settings_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let podfile = tmp.path().join("Podfile");
        std::fs::write(
            &podfile,
            r#"target 'App' do
  post_install do |installer|
    react_native_post_install(
      installer,
      config[:reactNativePath],
      :mac_catalyst_enabled => false,
    )
  end
end
"#,
        )
        .unwrap();
        patch_mesh_ios_podfile_build_settings(&podfile).unwrap();
        let first = std::fs::read_to_string(&podfile).unwrap();
        assert!(first.contains("FMT_USE_CONSTEVAL"));
        patch_mesh_ios_podfile_build_settings(&podfile).unwrap();
        assert_eq!(first, std::fs::read_to_string(&podfile).unwrap());
    }

    #[test]
    fn rewrite_shell_identity_renames_paths_and_contents() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let ios_dir = root.join("ios").join(CACHE_MODULE);
        let java_dir = root
            .join("android/app/src/main/java/com")
            .join(CACHE_MODULE.to_ascii_lowercase());
        std::fs::create_dir_all(&ios_dir).unwrap();
        std::fs::create_dir_all(&java_dir).unwrap();
        std::fs::write(
            ios_dir.join("AppDelegate.swift"),
            format!("// module {CACHE_MODULE}\npackage com.offlineshell\n"),
        )
        .unwrap();
        std::fs::write(
            java_dir.join("MainApplication.kt"),
            "package com.offlineshell\nclass MainApplication\n",
        )
        .unwrap();

        rewrite_shell_identity(root, "MyOfflineApp").unwrap();

        assert!(root.join("ios/MyOfflineApp/AppDelegate.swift").is_file());
        assert!(root
            .join("android/app/src/main/java/com/myofflineapp/MainApplication.kt")
            .is_file());
        let swift =
            std::fs::read_to_string(root.join("ios/MyOfflineApp/AppDelegate.swift")).unwrap();
        assert!(swift.contains("MyOfflineApp"));
        assert!(swift.contains("com.myofflineapp"));
        assert!(!swift.contains(CACHE_MODULE));
        let kt = std::fs::read_to_string(
            root.join("android/app/src/main/java/com/myofflineapp/MainApplication.kt"),
        )
        .unwrap();
        assert!(kt.contains("package com.myofflineapp"));
    }
}