juliaup 1.12.0

Julia installer and version multiplexer
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
use crate::config_file::load_mut_config_db;
use crate::config_file::save_config_db;
use crate::config_file::JuliaupConfig;
use crate::config_file::JuliaupConfigChannel;
use crate::config_file::JuliaupConfigVersion;
use crate::get_bundled_dbversion;
use crate::get_bundled_julia_version;
use crate::get_juliaup_target;
use crate::global_paths::GlobalPaths;
use crate::jsonstructs_versionsdb::JuliaupVersionDB;
use crate::utils::get_bin_dir;
use crate::utils::get_juliaserver_base_url;
use anyhow::{anyhow, bail, Context, Result};
use bstr::ByteSlice;
use bstr::ByteVec;
use console::style;
use flate2::read::GzDecoder;
use indicatif::{ProgressBar, ProgressStyle};
use indoc::formatdoc;
use semver::Version;
use std::io::BufReader;
use std::io::Seek;
use std::io::Write;
#[cfg(not(windows))]
use std::os::unix::fs::PermissionsExt;
use std::{
    io::Read,
    path::{Component::Normal, Path, PathBuf},
};
use tar::Archive;

fn unpack_sans_parent<R, P>(mut archive: Archive<R>, dst: P, levels_to_skip: usize) -> Result<()>
where
    R: Read,
    P: AsRef<Path>,
{
    for entry in archive.entries()? {
        let mut entry = entry?;
        let path: PathBuf = entry
            .path()?
            .components()
            .skip(levels_to_skip) // strip top-level directory
            .filter(|c| matches!(c, Normal(_))) // prevent traversal attacks TODO We should actually abort if we come across a non-standard path element
            .collect();
        entry.unpack(dst.as_ref().join(path))?;
    }
    Ok(())
}

#[cfg(not(windows))]
pub fn download_extract_sans_parent(
    url: &str,
    target_path: &Path,
    levels_to_skip: usize,
) -> Result<()> {
    let response = reqwest::blocking::get(url)
        .with_context(|| format!("Failed to download from url `{}`.", url))?;

    let content_length = response.content_length();

    let pb = match content_length {
        Some(content_length) => ProgressBar::new(content_length),
        None => ProgressBar::new_spinner(),
    };

    pb.set_prefix("  Downloading:");
    pb.set_style(
        ProgressStyle::default_bar()
            .template("{prefix:.cyan.bold} [{bar}] {bytes}/{total_bytes} eta: {eta}")
            .unwrap()
            .progress_chars("=> "),
    );

    let foo = pb.wrap_read(response);

    let tar = GzDecoder::new(foo);
    let archive = Archive::new(tar);
    unpack_sans_parent(archive, target_path, levels_to_skip)
        .with_context(|| format!("Failed to extract downloaded file from url `{}`.", url))?;
    Ok(())
}

#[cfg(windows)]
struct DataReaderWrap(windows::Storage::Streams::DataReader);

#[cfg(windows)]
impl std::io::Read for DataReaderWrap {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let mut bytes =
            self.0
                .LoadAsync(buf.len() as u32)
                .map_err(|e| std::io::Error::from_raw_os_error(e.code().0))?
                .get()
                .map_err(|e| std::io::Error::from_raw_os_error(e.code().0))? as usize;
        bytes = bytes.min(buf.len());
        self.0
            .ReadBytes(&mut buf[0..bytes])
            .map_err(|e| std::io::Error::from_raw_os_error(e.code().0))
            .map(|_| bytes)
    }
}

#[cfg(windows)]
pub fn download_extract_sans_parent(
    url: &str,
    target_path: &Path,
    levels_to_skip: usize,
) -> Result<()> {
    let http_client =
        windows::Web::Http::HttpClient::new().with_context(|| "Failed to create HttpClient.")?;

    let request_uri = windows::Foundation::Uri::CreateUri(&windows::core::HSTRING::from(url))
        .with_context(|| "Failed to convert url string to Uri.")?;

    let http_response = http_client
        .GetAsync(&request_uri)
        .with_context(|| "Failed to initiate download.")?
        .get()
        .with_context(|| "Failed to complete async download operation.")?;

    http_response
        .EnsureSuccessStatusCode()
        .with_context(|| "HTTP download reported error status code.")?;

    let http_response_content = http_response
        .Content()
        .with_context(|| "Failed to obtain content from http response.")?;

    let response_stream = http_response_content
        .ReadAsInputStreamAsync()
        .with_context(|| "Failed to initiate get input stream from response")?
        .get()
        .with_context(|| "Failed to obtain input stream from http response")?;

    let reader = windows::Storage::Streams::DataReader::CreateDataReader(&response_stream)
        .with_context(|| "Failed to create DataReader.")?;

    reader
        .SetInputStreamOptions(windows::Storage::Streams::InputStreamOptions::ReadAhead)
        .with_context(|| "Failed to set input stream options.")?;

    let mut content_length: u64 = 0;
    let pb = if http_response_content.TryComputeLength(&mut content_length)? {
        ProgressBar::new(content_length)
    } else {
        ProgressBar::new_spinner()
    };

    pb.set_prefix("  Downloading:");
    pb.set_style(
        ProgressStyle::default_bar()
            .template("{prefix:.cyan.bold} [{bar}] {bytes}/{total_bytes} eta: {eta}")
            .unwrap()
            .progress_chars("=> "),
    );

    let foo = pb.wrap_read(DataReaderWrap(reader));

    let tar = GzDecoder::new(foo);

    let archive = Archive::new(tar);

    unpack_sans_parent(archive, &target_path, levels_to_skip)
        .with_context(|| format!("Failed to extract downloaded file from url `{}`.", url))?;

    Ok(())
}

#[cfg(not(windows))]
pub fn download_juliaup_version(url: &str) -> Result<Version> {
    let response = reqwest::blocking::get(url)
        .with_context(|| format!("Failed to download from url `{}`.", url))?
        .text()?;

    let version = Version::parse(&response.trim()).with_context(|| {
        format!(
            "`download_juliaup_version` failed to parse `{}` as a valid semversion.",
            response.trim()
        )
    })?;

    Ok(version)
}

#[cfg(not(windows))]
pub fn download_versiondb(url: &str, path: &Path) -> Result<()> {
    let mut response = reqwest::blocking::get(url)
        .with_context(|| format!("Failed to download from url `{}`.", url))?;

    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(path)
        .with_context(|| format!("Failed to open or create version db file at {:?}", path))?;
    let mut buf: Vec<u8> = vec![];
    response.copy_to(&mut buf)?;
    file.write_all(buf.as_slice())
        .with_context(|| "Failed to write content into version db file.")?;

    Ok(())
}

#[cfg(windows)]
pub fn download_juliaup_version(url: &str) -> Result<Version> {
    let http_client =
        windows::Web::Http::HttpClient::new().with_context(|| "Failed to create HttpClient.")?;

    let request_uri = windows::Foundation::Uri::CreateUri(&windows::core::HSTRING::from(url))
        .with_context(|| "Failed to convert url string to Uri.")?;

    let response = http_client
        .GetStringAsync(&request_uri)
        .with_context(|| "Failed on http_client.GetStringAsync")?
        .get()
        .with_context(|| "Failed on http_client.GetStringAsync.get")?
        .to_string();

    let trimmed_response = response.trim();

    let version = Version::parse(trimmed_response).with_context(|| {
        format!(
            "`download_juliaup_version` failed to parse `{}` as a valid semversion.",
            trimmed_response
        )
    })?;

    Ok(version)
}

#[cfg(windows)]
pub fn download_versiondb(url: &str, path: &Path) -> Result<()> {
    let http_client =
        windows::Web::Http::HttpClient::new().with_context(|| "Failed to create HttpClient.")?;

    let request_uri = windows::Foundation::Uri::CreateUri(&windows::core::HSTRING::from(url))
        .with_context(|| "Failed to convert url string to Uri.")?;

    let response = http_client
        .GetStringAsync(&request_uri)
        .with_context(|| "Failed to download version db step 1.")?
        .get()
        .with_context(|| "Failed to download version db step 2.")?
        .to_string();

    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(&path)
        .with_context(|| format!("Failed to open or create version db file at {:?}", path))?;

    file.write_all(response.as_bytes())
        .with_context(|| "Failed to write content into version db file.")?;

    Ok(())
}

pub fn install_version(
    fullversion: &String,
    config_data: &mut JuliaupConfig,
    version_db: &JuliaupVersionDB,
    paths: &GlobalPaths,
) -> Result<()> {
    // Return immediately if the version is already installed.
    if config_data.installed_versions.contains_key(fullversion) {
        return Ok(());
    }

    // TODO At some point we could put this behind a conditional compile, we know
    // that we don't ship a bundled version for some platforms.
    let full_version_string_of_bundled_version = get_bundled_julia_version();
    let my_own_path = std::env::current_exe()?;
    let path_of_bundled_version = my_own_path
        .parent()
        .unwrap() // unwrap OK because we can't get a path that does not have a parent
        .join("BundledJulia");

    let child_target_foldername = format!("julia-{}", fullversion);
    let target_path = paths.juliauphome.join(&child_target_foldername);
    std::fs::create_dir_all(target_path.parent().unwrap())?;

    if fullversion == full_version_string_of_bundled_version && path_of_bundled_version.exists() {
        let mut options = fs_extra::dir::CopyOptions::new();
        options.overwrite = true;
        options.content_only = true;
        fs_extra::dir::copy(path_of_bundled_version, target_path, &options)?;
    } else {
        let juliaupserver_base =
            get_juliaserver_base_url().with_context(|| "Failed to get Juliaup server base URL.")?;

        let download_url_path = &version_db
            .available_versions
            .get(fullversion)
            .ok_or_else(|| {
                anyhow!(
                    "Failed to find download url in versions db for '{}'.",
                    fullversion
                )
            })?
            .url_path;

        let download_url = juliaupserver_base
            .join(download_url_path)
            .with_context(|| {
                format!(
                    "Failed to construct a valid url from '{}' and '{}'.",
                    juliaupserver_base, download_url_path
                )
            })?;

        eprintln!(
            "{} Julia {}",
            style("Installing").green().bold(),
            fullversion
        );

        download_extract_sans_parent(download_url.as_ref(), &target_path, 1)?;
    }

    let mut rel_path = PathBuf::new();
    rel_path.push(".");
    rel_path.push(&child_target_foldername);

    config_data.installed_versions.insert(
        fullversion.clone(),
        JuliaupConfigVersion {
            path: rel_path.to_string_lossy().into_owned(),
        },
    );

    Ok(())
}

pub fn garbage_collect_versions(
    config_data: &mut JuliaupConfig,
    paths: &GlobalPaths,
) -> Result<()> {
    let mut versions_to_uninstall: Vec<String> = Vec::new();
    for (installed_version, detail) in &config_data.installed_versions {
        if config_data.installed_channels.iter().all(|j| match &j.1 {
            JuliaupConfigChannel::SystemChannel { version } => version != installed_version,
            JuliaupConfigChannel::LinkedChannel {
                command: _,
                args: _,
            } => true,
        }) {
            let path_to_delete = paths.juliauphome.join(&detail.path);
            let display = path_to_delete.display();

            if std::fs::remove_dir_all(&path_to_delete).is_err() {
                eprintln!("WARNING: Failed to delete {}. You can try to delete at a later point by running `juliaup gc`.", display)
            }
            versions_to_uninstall.push(installed_version.clone());
        }
    }

    for i in versions_to_uninstall {
        config_data.installed_versions.remove(&i);
    }

    Ok(())
}

fn _remove_symlink(symlink_path: &Path) -> Result<()> {
    std::fs::create_dir_all(symlink_path.parent().unwrap())?;

    if symlink_path.exists() {
        std::fs::remove_file(symlink_path)?;
    }

    Ok(())
}

pub fn remove_symlink(symlink_name: &String) -> Result<()> {
    let symlink_path = get_bin_dir()
        .with_context(|| "Failed to retrieve binary directory while trying to remove a symlink.")?
        .join(symlink_name);

    eprintln!(
        "{} {}.",
        style("Deleting symlink").cyan().bold(),
        symlink_name
    );

    _remove_symlink(&symlink_path)?;

    Ok(())
}

#[cfg(not(windows))]
pub fn create_symlink(
    channel: &JuliaupConfigChannel,
    symlink_name: &String,
    paths: &GlobalPaths,
) -> Result<()> {
    let symlink_folder = get_bin_dir()
        .with_context(|| "Failed to retrieve binary directory while trying to create a symlink.")?;

    let symlink_path = symlink_folder.join(symlink_name);

    _remove_symlink(&symlink_path)?;

    match channel {
        JuliaupConfigChannel::SystemChannel { version } => {
            let child_target_fullname = format!("julia-{}", version);

            let target_path = paths.juliauphome.join(&child_target_fullname);

            eprintln!(
                "{} {} for Julia {}.",
                style("Creating symlink").cyan().bold(),
                symlink_name,
                version
            );

            std::os::unix::fs::symlink(target_path.join("bin").join("julia"), &symlink_path)
                .with_context(|| {
                    format!(
                        "failed to create symlink `{}`.",
                        symlink_path.to_string_lossy()
                    )
                })?;
        }
        JuliaupConfigChannel::LinkedChannel { command, args } => {
            let formatted_command = match args {
                Some(x) => format!("{} {}", command, x.join(" ")),
                None => command.clone(),
            };

            eprintln!(
                "{} {} for `{}`",
                style("Creating shim").cyan().bold(),
                symlink_name,
                formatted_command
            );

            std::fs::write(
                &symlink_path,
                format!(
                    r#"#!/bin/sh
{} "$@"
"#,
                    formatted_command,
                ),
            )
            .with_context(|| {
                format!(
                    "failed to create shim `{}`.",
                    symlink_path.to_string_lossy()
                )
            })?;

            // set as executable
            let perms = std::fs::Permissions::from_mode(0o755);
            std::fs::set_permissions(&symlink_path, perms).with_context(|| {
                format!(
                    "failed to change permissions for shim `{}`.",
                    symlink_path.to_string_lossy()
                )
            })?;
        }
    };

    if let Ok(path) = std::env::var("PATH") {
        if !path.split(':').any(|p| Path::new(p) == symlink_folder) {
            eprintln!(
                "Symlink {} added in {}. Add this directory to the system PATH to make the command available in your shell.",
                &symlink_name, symlink_folder.display(),
            );
        }
    }

    Ok(())
}

#[cfg(windows)]
pub fn create_symlink(_: &JuliaupConfigChannel, _: &String, _paths: &GlobalPaths) -> Result<()> {
    Ok(())
}

#[cfg(feature = "selfupdate")]
pub fn install_background_selfupdate(interval: i64) -> Result<()> {
    use itertools::Itertools;
    use std::process::Stdio;

    let own_exe_path = std::env::current_exe()
        .with_context(|| "Could not determine the path of the running exe.")?;

    let my_own_path = own_exe_path.to_str().unwrap();

    match std::env::var("WSL_DISTRO_NAME") {
        // This is the WSL case, where we schedule a Windows task to do the update
        Ok(val) => {
            std::process::Command::new("schtasks.exe")
                .args([
                    "/create",
                    "/sc",
                    "minute",
                    "/mo",
                    &interval.to_string(),
                    "/tn",
                    &format!("Juliaup self update for WSL {} distribution", val),
                    "/f",
                    "/it",
                    "/tr",
                    &format!("wsl --distribution {} {} self update", val, my_own_path),
                ])
                .output()
                .with_context(|| "Failed to create new Windows task for juliaup.")?;
        }
        Err(_e) => {
            let output = std::process::Command::new("crontab")
                .args(["-l"])
                .output()
                .with_context(|| "Failed to retrieve crontab configuration.")?;

            let new_crontab_content = String::from_utf8(output.stdout)?
                .lines()
                .filter(|x| !x.contains("4c79c12db1d34bbbab1f6c6f838f423f"))
                .chain([
                    &format!(
                        "*/{} * * * * {} 4c79c12db1d34bbbab1f6c6f838f423f",
                        interval, my_own_path
                    ),
                    "",
                ])
                .join("\n");

            let mut child = std::process::Command::new("crontab")
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()?;

            let child_stdin = child.stdin.as_mut().unwrap();

            child_stdin.write_all(new_crontab_content.as_bytes())?;

            // Close stdin to finish and avoid indefinite blocking
            drop(child_stdin);

            child.wait_with_output()?;
        }
    };

    Ok(())
}

#[cfg(feature = "selfupdate")]
pub fn uninstall_background_selfupdate() -> Result<()> {
    use itertools::Itertools;
    use std::process::Stdio;

    match std::env::var("WSL_DISTRO_NAME") {
        // This is the WSL case, where we schedule a Windows task to do the update
        Ok(val) => {
            std::process::Command::new("schtasks.exe")
                .args([
                    "/delete",
                    "/tn",
                    &format!("Juliaup self update for WSL {} distribution", val),
                    "/f",
                ])
                .output()
                .with_context(|| "Failed to remove Windows task for juliaup.")?;
        }
        Err(_e) => {
            let output = std::process::Command::new("crontab")
                .args(["-l"])
                .output()
                .with_context(|| "Failed to remove cron task.")?;

            let new_crontab_content = String::from_utf8(output.stdout)?
                .lines()
                .filter(|x| !x.contains("4c79c12db1d34bbbab1f6c6f838f423f"))
                .chain([""])
                .join("\n");

            let mut child = std::process::Command::new("crontab")
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .spawn()?;

            let child_stdin = child.stdin.as_mut().unwrap();

            child_stdin.write_all(new_crontab_content.as_bytes())?;

            // Close stdin to finish and avoid indefinite blocking
            drop(child_stdin);

            child.wait_with_output()?;
        }
    };

    Ok(())
}

const S_MARKER: &[u8] = b"# >>> juliaup initialize >>>";
const E_MARKER: &[u8] = b"# <<< juliaup initialize <<<";
const HEADER: &[u8] = b"\n\n# !! Contents within this block are managed by juliaup !!\n\n";

fn get_shell_script_juliaup_content(bin_path: &Path, path: &Path) -> Result<Vec<u8>> {
    let mut result: Vec<u8> = Vec::new();

    let bin_path_str = match bin_path.to_str() {
        Some(s) => s,
        None =>  bail!("Could not create UTF-8 string from passed-in binary application path. Currently only valid UTF-8 paths are supported"),
    };

    result.extend_from_slice(S_MARKER);
    result.extend_from_slice(HEADER);
    if path.file_name().unwrap() == ".zshrc" {
        append_zsh_content(&mut result, bin_path_str);
    } else {
        append_sh_content(&mut result, bin_path_str);
    }
    result.extend_from_slice(b"\n");
    result.extend_from_slice(E_MARKER);

    Ok(result)
}

fn append_zsh_content(buf: &mut Vec<u8>, path_str: &str) {
    // zsh specific syntax for path extension
    let content = formatdoc!(
        "
            path=('{}' $path)
            export PATH
        ",
        path_str
    );

    buf.extend_from_slice(content.as_bytes());
}

fn append_sh_content(buf: &mut Vec<u8>, path_str: &str) {
    // If the variable is already contained in $PATH, do nothing
    // Otherwise prepend it to path
    // ${PATH:+:${PATH}} => Only append :$PATH if $PATH is set
    let content = formatdoc!(
        "
            case \":$PATH:\" in
                *:{0}:*)
                    ;;

                *)
                    export PATH={0}${{PATH:+:${{PATH}}}}
                    ;;
            esac
        ",
        path_str
    );
    buf.extend_from_slice(content.as_bytes());
}

fn match_markers(buffer: &[u8]) -> Result<Option<(usize, usize)>> {
    let start_marker = buffer.find(S_MARKER);
    let end_marker = buffer.find(E_MARKER);

    // This ensures exactly one opening and one closing marker exists
    let (start_marker, end_marker) = match (start_marker, end_marker) {
        (Some(sidx), Some(eidx)) => {
            if sidx != buffer.rfind(S_MARKER).unwrap() || eidx != buffer.rfind(E_MARKER).unwrap() {
                bail!("Found multiple startup script sections from juliaup.");
            }
            (sidx, eidx)
        }
        (None, None) => {
            return Ok(None);
        }
        (_, None) => {
            bail!("Found an opening marker but no end marker of juliaup section.");
        }
        (None, _) => {
            bail!("Found an opening marker but no end marker of juliaup section.");
        }
    };

    Ok(Some((start_marker, end_marker + E_MARKER.len())))
}

fn add_path_to_specific_file(bin_path: &Path, path: &Path) -> Result<()> {
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open(path)
        .with_context(|| format!("Failed to open file {}.", path.display()))?;

    let mut buffer: Vec<u8> = Vec::new();

    file.read_to_end(&mut buffer)
        .with_context(|| format!("Failed to read data from file {}.", path.display()))?;

    let existing_code_pos = match_markers(&buffer).with_context(|| {
        format!(
            "Error occured while searching juliaup shell startup script section in {}",
            path.display()
        )
    })?;

    let new_content = get_shell_script_juliaup_content(bin_path, &path).with_context(|| {
        format!(
            "Error occured while generating juliaup shell startup script section for {}",
            path.display()
        )
    })?;

    match existing_code_pos {
        Some(pos) => {
            buffer.replace_range(pos.0..pos.1, &new_content);
        }
        None => {
            buffer.extend_from_slice(b"\n");
            buffer.extend_from_slice(&new_content);
            buffer.extend_from_slice(b"\n");
        }
    };

    file.rewind().unwrap();

    file.set_len(0).unwrap();

    file.write_all(&buffer).unwrap();

    file.sync_all().unwrap();

    Ok(())
}

fn remove_path_from_specific_file(path: &Path) -> Result<()> {
    let mut file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(path)
        .with_context(|| format!("Failed to open file: {}", path.display()))?;

    let mut buffer: Vec<u8> = Vec::new();

    file.read_to_end(&mut buffer)?;

    let existing_code_pos = match_markers(&buffer).with_context(|| {
        format!(
            "Error occured while searching juliaup shell startup script section in {}",
            path.display()
        )
    })?;

    if let Some(pos) = existing_code_pos {
        buffer.replace_range(pos.0..pos.1, "");

        file.rewind().unwrap();

        file.set_len(0).unwrap();

        file.write_all(&buffer).unwrap();

        file.sync_all().unwrap();
    }

    Ok(())
}

pub fn find_shell_scripts_to_be_modified(add_case: bool) -> Result<Vec<PathBuf>> {
    let home_dir = dirs::home_dir().unwrap();

    let paths_to_test: Vec<PathBuf> = vec![
        home_dir.join(".bashrc"),
        home_dir.join(".profile"),
        home_dir.join(".bash_profile"),
        home_dir.join(".bash_login"),
        home_dir.join(".zshrc"),
    ];

    let result = paths_to_test
        .iter()
        .filter(
            |p| {
                p.exists()
                    || (add_case
                        && p.file_name().unwrap() == ".zshrc"
                        && std::env::consts::OS == "macos")
            }, // On MacOS, always edit .zshrc as that is the default shell, but only when we add things
        )
        .cloned()
        .collect();
    Ok(result)
}

pub fn add_binfolder_to_path_in_shell_scripts(bin_path: &Path) -> Result<()> {
    let paths = find_shell_scripts_to_be_modified(true)?;

    paths.into_iter().for_each(|p| {
        add_path_to_specific_file(bin_path, &p).unwrap();
    });
    Ok(())
}

pub fn remove_binfolder_from_path_in_shell_scripts() -> Result<()> {
    let paths = find_shell_scripts_to_be_modified(false)?;

    paths.into_iter().for_each(|p| {
        remove_path_from_specific_file(&p).unwrap();
    });
    Ok(())
}

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

    #[test]
    fn match_markers_none_without_markers() {
        let inp: &[u8] = b"Some input\n";
        let res = match_markers(inp);
        assert!(res.is_ok());
        let res = res.unwrap();
        assert!(res.is_none());
    }

    #[test]
    fn match_markers_returns_correct_indices() {
        let mut inp: Vec<u8> = Vec::new();
        let start_bytes = b"Some random bytes.";
        let middle_bytes = b"More bytes.";
        let end_bytes = b"Final bytes.";
        inp.extend_from_slice(start_bytes);
        inp.extend_from_slice(S_MARKER);
        inp.extend_from_slice(middle_bytes);
        inp.extend_from_slice(E_MARKER);
        inp.extend_from_slice(end_bytes);

        // Verify Ok(Some(..)) is returned
        let res = match_markers(&inp);
        assert!(res.is_ok());
        let res = res.unwrap();
        assert!(res.is_some());
        let (sidx, eidx) = res.unwrap();

        // Verify correct positions
        assert_eq!(sidx, start_bytes.len());
        let expected_eidx =
            start_bytes.len() + S_MARKER.len() + middle_bytes.len() + E_MARKER.len();
        assert_eq!(eidx, expected_eidx);
    }

    #[test]
    fn match_markers_returns_err_without_start() {
        let mut inp: Vec<u8> = Vec::new();
        let start_bytes = b"Some random bytes.";
        let middle_bytes = b"More bytes.";
        let end_bytes = b"Final bytes.";
        inp.extend_from_slice(start_bytes);
        inp.extend_from_slice(middle_bytes);
        inp.extend_from_slice(E_MARKER);
        inp.extend_from_slice(end_bytes);

        // Verify Err(..) is returned
        let res = match_markers(&inp);
        assert!(res.is_err());
    }

    #[test]
    fn match_markers_returns_err_without_end() {
        let mut inp: Vec<u8> = Vec::new();
        let start_bytes = b"Some random bytes.";
        let middle_bytes = b"More bytes.";
        let end_bytes = b"Final bytes.";
        inp.extend_from_slice(start_bytes);
        inp.extend_from_slice(S_MARKER);
        inp.extend_from_slice(middle_bytes);
        inp.extend_from_slice(end_bytes);

        // Verify Err(..) is returned
        let res = match_markers(&inp);
        assert!(res.is_err());
    }

    #[test]
    fn match_markers_returns_err_with_multiple_start() {
        let mut inp: Vec<u8> = Vec::new();
        let start_bytes = b"Some random bytes.";
        let middle_bytes = b"More bytes.";
        let end_bytes = b"Final bytes.";
        inp.extend_from_slice(S_MARKER);
        inp.extend_from_slice(start_bytes);
        inp.extend_from_slice(S_MARKER);
        inp.extend_from_slice(middle_bytes);
        inp.extend_from_slice(E_MARKER);
        inp.extend_from_slice(end_bytes);

        // Verify Err(..) is returned
        let res = match_markers(&inp);
        assert!(res.is_err());
    }

    #[test]
    fn match_markers_returns_err_with_multiple_end() {
        let mut inp: Vec<u8> = Vec::new();
        let start_bytes = b"Some random bytes.";
        let middle_bytes = b"More bytes.";
        let end_bytes = b"Final bytes.";
        inp.extend_from_slice(start_bytes);
        inp.extend_from_slice(S_MARKER);
        inp.extend_from_slice(middle_bytes);
        inp.extend_from_slice(E_MARKER);
        inp.extend_from_slice(end_bytes);
        inp.extend_from_slice(E_MARKER);

        // Verify Err(..) is returned
        let res = match_markers(&inp);
        assert!(res.is_err());
    }
}

pub fn update_version_db(paths: &GlobalPaths) -> Result<()> {
    let mut config_file = load_mut_config_db(paths).with_context(|| {
        "`run_command_update_version_db` command failed to load configuration db."
    })?;

    #[cfg(feature = "selfupdate")]
    let juliaup_channel = match &config_file.self_data.juliaup_channel {
        Some(juliaup_channel) => juliaup_channel.to_string(),
        None => "release".to_string(),
    };

    // TODO Figure out how we can learn about the correctn Juliaup channel here
    #[cfg(not(feature = "selfupdate"))]
    let juliaup_channel = "release".to_string();

    let juliaupserver_base =
        get_juliaserver_base_url().with_context(|| "Failed to get Juliaup server base URL.")?;

    let dbversion_url_path = match juliaup_channel.as_str() {
        "release" => "juliaup/RELEASECHANNELDBVERSION",
        "releasepreview" => "juliaup/RELEASEPREVIEWCHANNELDBVERSION",
        "dev" => "juliaup/DEVCHANNELDBVERSION",
        _ => bail!(
            "Juliaup is configured to a channel named '{}' that does not exist.",
            &juliaup_channel
        ),
    };

    let dbversion_url = juliaupserver_base
        .join(dbversion_url_path)
        .with_context(|| {
            format!(
                "Failed to construct a valid url from '{}' and '{}'.",
                juliaupserver_base, dbversion_url_path
            )
        })?;

    let online_dbversion = download_juliaup_version(&dbversion_url.to_string())
        .with_context(|| "Failed to download current version db version.")?;

    config_file.data.last_version_db_update = Some(chrono::Utc::now());

    save_config_db(&mut config_file).with_context(|| "Failed to save configuration file.")?;

    let bundled_dbversion = get_bundled_dbversion()
        .with_context(|| "Failed to determine the bundled version db version.")?;

    let local_dbversion = match std::fs::OpenOptions::new()
        .read(true)
        .open(&paths.versiondb)
    {
        Ok(file) => {
            let reader = BufReader::new(&file);

            if let Ok(versiondb) =
                serde_json::from_reader::<BufReader<&std::fs::File>, JuliaupVersionDB>(reader)
            {
                if let Ok(version) = semver::Version::parse(&versiondb.version) {
                    Some(version)
                } else {
                    None
                }
            } else {
                None
            }
        }
        Err(_) => None,
    };

    if online_dbversion > bundled_dbversion {
        if local_dbversion.is_none() || online_dbversion > local_dbversion.unwrap() {
            let onlineversiondburl = juliaupserver_base
                .join(&format!(
                    "juliaup/versiondb/versiondb-{}-{}.json",
                    online_dbversion,
                    get_juliaup_target()
                ))
                .with_context(|| "Failed to construct URL for version db download.")?;

            download_versiondb(&onlineversiondburl.to_string(), &paths.versiondb).with_context(
                || {
                    format!(
                        "Failed to download new version db from {}.",
                        onlineversiondburl
                    )
                },
            )?;
        }
    } else if local_dbversion.is_some() {
        // If the bundled version is up-to-date we can delete any cached version db json file
        let _ = std::fs::remove_file(&paths.versiondb);
    }

    Ok(())
}