[go: up one dir, main page]

arch 0.3.0

A archlinux installer and manager
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
#![allow(clippy::multiple_crate_versions)]

use inquire::{prompt_confirmation, Confirm, MultiSelect, Password, Select, Text};
use regex::Regex;
use std::collections::HashMap;
use std::env::args;
use std::fs::File;
use std::io;
use std::io::Write;
use std::io::{read_to_string, BufRead};
use std::path::Path;
use std::process::{exit, Command, ExitCode};
fn exec(cmd: &str, args: &[&str]) -> bool {
    Command::new(cmd)
        .args(args)
        .spawn()
        .unwrap()
        .wait()
        .expect("failed to execute cmd")
        .success()
}

///
/// # Panics
///
fn read_lines(filename: &str) -> io::Lines<io::BufReader<File>> {
    let file = File::open(filename).expect("failed to open filename");
    io::BufReader::new(file).lines()
}
fn parse_file_lines(filename: &str) -> Vec<String> {
    let mut file_lines: Vec<String> = Vec::new();
    read_lines(filename).for_each(|line| match line {
        Ok(l) => {
            // perform some logic here...
            file_lines.push(l);
        }
        Err(x) => println!("{x}"),
    });
    file_lines
}
pub struct Arch {
    locales: Vec<String>,
    profile: String,
    lang: String,
    packages: Vec<String>,
    root: HashMap<bool, String>,
    users: Vec<Users>,
    users_table: Vec<Users>,
    timezone: String,
    keymap: String,
    hostname: String,
}

#[derive(Clone)]
pub struct Users {
    name: String,
    password: String,
    shell: String,
    sudoers: bool,
}

impl Users {
    #[must_use]
    pub const fn new(name: String, password: String, shell: String, sudoers: bool) -> Self {
        Self {
            name,
            password,
            shell,
            sudoers,
        }
    }
}

impl Default for Arch {
    #[must_use]
    fn default() -> Self {
        Self {
            locales: Vec::new(),
            lang: String::new(),
            packages: Vec::new(),
            root: HashMap::new(),
            users: Vec::new(),
            users_table: Vec::new(),
            timezone: String::new(),
            keymap: String::new(),
            profile: String::new(),
            hostname: String::new(),
        }
    }
}
impl Arch {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
    ///
    /// # Panics
    ///
    pub fn systemd(&mut self) -> &mut Self {
        assert!(
            exec(
                "sh",
                &["-c","wget -q https://raw.githubusercontent.com/otechdo/arch/main/arch/systemd/arch.service"]
            ),
            "Failed to download arch.service"
        );
        assert!(
            exec(
                "sh",
                &["-c","wget -q https://raw.githubusercontent.com/otechdo/arch/main/arch/systemd/arch.timer"]
            ),
            "Failed to download arch.timer"
        );
        assert!(
            exec(
                "sh",
                &[
                    "-c",
                    "sudo install -m 644 arch.timer /etc/systemd/system/arch.timer"
                ]
            ),
            "Failed to install arch.timer"
        );
        assert!(
            exec(
                "sh",
                &[
                    "-c",
                    "sudo install -m 644 arch.service /etc/systemd/system/arch.service"
                ]
            ),
            "Failed to install arch.service"
        );
        assert!(
            exec("sh", &["-c", "sudo systemctl enable arch.service"]),
            "Failed to enable arch.service"
        );
        assert!(
            exec("sh", &["-c", "sudo systemctl enable arch.timer"]),
            "Failed to enable arch.timer"
        );
        self
    }

    ///
    /// # Panics
    ///
    pub fn dotfiles(&mut self) -> &mut Self {
        let dot = prompt_confirmation("Clone a dotfiles repository ?").unwrap();
        let mut cmds: Vec<String> = Vec::new();
        if dot {
            if Path::new("dotfiles").exists() {
                assert!(exec("sh", &["-c", "rm -rf dotfiles"]));
            }
            let repo = Text::new("Enter repository url : ")
                .with_help_message("Url must be a git repository")
                .prompt()
                .unwrap();
            assert!(
                exec(
                    "sh",
                    &["-c", format!("git clone --quiet {repo} dotfiles").as_str()]
                ),
                "Failed to download your dotfiles repository"
            );

            loop {
                let cmd = Text::new("Please enter a bash command : ")
                    .prompt()
                    .unwrap();
                cmds.push(cmd);
                match prompt_confirmation("Add a new command ? ") {
                    Ok(true) => continue,
                    Ok(false) | Err(_) => break,
                }
            }
            for cmd in &cmds {
                let collection: Vec<&str> = cmd.split_whitespace().collect();
                assert!(Command::new("bash")
                    .args(collection)
                    .current_dir("dotfiles")
                    .spawn()
                    .unwrap()
                    .wait()
                    .unwrap()
                    .success());
            }
            assert!(
                exec("sh", &["-c", "rm -rf dotfiles"]),
                "Failed to remove dotefiles directory"
            );
            return self;
        }
        self
    }

    ///
    ///  # Panics
    ///
    fn install_package(&mut self) -> &mut Self {
        for pkg in &self.packages {
            assert!(
                exec("sh", &["-c", format!("yay -S --noconfirm {pkg}").as_str()]),
                "{}",
                format!("Failed to install the {pkg}").as_str()
            );
        }
        self
    }

    ///
    ///  # Panics
    ///
    fn install_dependencies(&mut self) -> &mut Self {
        for pkg in &self.packages {
            assert!(
                exec(
                    "sh",
                    &["-c", format!("yay -S {pkg} --noconfirm --asdeps").as_str()]
                ),
                "{}",
                format!("Failed to install {pkg} dependency").as_str()
            );
        }
        self
    }

    ///
    ///  # Panics
    ///
    fn remove_package(&mut self) -> &mut Self {
        for pkg in &self.packages {
            assert!(
                exec("sh", &["-c", format!("yay -Rns {pkg}").as_str()]),
                "{}",
                format!("Failed to remove {pkg} dependency").as_str()
            );
        }
        self
    }

    ///
    /// # Panics
    ///
    pub fn quit_installer(&mut self) -> ExitCode {
        exit(self.configure_boot().enable_services());
    }

    pub fn quit(&mut self, t: &str) -> ExitCode {
        println!("{t}");
        exit(0);
    }

    ///
    /// # Panics
    ///
    pub fn enable_services(&mut self) -> i32 {
        assert!(exec(
            "sh",
            &["-c", "sudo systemctl enable NetworkManager.service"]
        ));
        assert!(exec(
            "sh",
            &[
                "-c",
                "sudo systemctl enable NetworkManager-wait-online.service"
            ]
        ));
        0
    }

    ///
    /// if failed to get locale
    ///
    pub fn choose_language(&mut self) -> &mut Self {
        let mut locales: Vec<String> = Vec::new();
        self.lang.clear();
        let text =
            read_to_string(File::open("/etc/locale.gen").expect("failed to open locale file"))
                .expect("failed to get file content");
        let re = Regex::new(r"[a-z]{2}_[A-Z]{2}[.][A-Z]{3}-[0-9]").unwrap(); // \d means digit
        for mat in re.find_iter(text.as_str()) {
            locales.push(mat.as_str().to_string());
        }
        let locale = Select::new("Choose your system language : ", locales.clone())
            .prompt()
            .expect("Failed to get locales");
        if locale.is_empty() {
            self.choose_language()
        } else {
            self.lang = locale.to_string();

            self
        }
    }

    ///
    /// if failed to get locale
    ///
    pub fn choose_locales(&mut self) -> &mut Self {
        let mut locales: Vec<String> = Vec::new();
        self.locales.clear();
        let text =
            read_to_string(File::open("/etc/locale.gen").expect("failed to open locale file"))
                .expect("failed to get file content");
        let re = Regex::new(r"[a-z]{2}_[A-Z]{2}[.][A-Z]{3}-[0-9]").unwrap(); // \d means digit
        for mat in re.find_iter(text.as_str()) {
            locales.push(mat.as_str().to_string());
        }
        let locale = MultiSelect::new("Choose your system locales : ", locales.clone())
            .prompt()
            .expect("Failed to get locales");
        if locales.is_empty() {
            self.choose_locales()
        } else {
            for l in locale {
                self.locales.push(l.to_string());
            }

            self
        }
    }

    ///
    /// # Panics
    ///
    pub fn wiki(&mut self) -> &mut Self {
        assert!(exec("sh", &["-c", "w3m wiki.archlinux.org"]));
        self
    }

    ///
    /// # Panics
    ///
    pub fn news(&mut self) -> &mut Self {
        assert!(exec("sh", &["-c", "w3m archlinux.org/news"]));
        self
    }

    ///
    /// # Panics
    ///
    pub fn choose_keymap(&mut self) -> &mut Self {
        let keymap = Text::new("Please enter your keymap : ").prompt().unwrap();
        if keymap.is_empty() {
            return self.choose_keymap();
        }
        self.keymap.clear();
        self.keymap.push_str(keymap.as_str());
        self
    }

    ///
    /// # Panics
    ///
    pub fn configure_timezone(&mut self) -> &mut Self {
        assert!(exec(
            "sh",
            &[
                "-c",
                format!(
                    "sudo ln -svf /usr/share/zoneinfo/{} /etc/localtime",
                    self.timezone
                )
                .as_str()
            ]
        ));
        self
    }

    ///
    /// # Panics
    ///
    pub fn forums(&mut self) -> &mut Self {
        assert!(exec("sh", &["-c", "w3m bbs.archlinux.org"]));
        self
    }

    ///
    /// # Panics
    ///
    pub fn check_network(&mut self) -> &mut Self {
        println!("Checking network...");
        assert!(exec(
            "sh",
            &["-c", "ping -4c4 archlinux.org > /dev/null 2> /dev/null"]
        ));
        self
    }

    ///
    /// # Panics
    ///
    pub fn configure_keymap(&mut self) -> &mut Self {
        let mut keymap = File::create("vconsole.conf").expect("failed to cretae the keymap file");
        keymap
            .write_all(format!("KEYMAP={}\nXKBLAYOUT={}", self.keymap, self.keymap).as_bytes())
            .expect("failed to write data");
        keymap.sync_all().expect("failed to sync to disk");
        keymap.sync_data().expect("failed save to disk");

        assert!(exec(
            "sh",
            &["-c", "sudo install -m 644 vconsole.conf /etc/vconsole.conf"]
        ));

        assert!(exec("sh", &["-c", "sudo rm vconsole.conf"]));
        self
    }

    ///
    /// # Panics
    ///
    pub fn configure_locale(&mut self) -> &mut Self {
        let mut locale = File::create("locale.conf").expect("failed to cretae the locale file");
        locale
            .write_all(
                format!(
                    "LANG={}\nLC_COLLATE=C\nLANGUAGE={}\nLC_TIME={}",
                    self.lang, self.lang, self.lang
                )
                .as_bytes(),
            )
            .expect("failed to write data");
        locale.sync_all().expect("failed to sync to disk");
        locale.sync_data().expect("failed save to disk");

        assert!(exec(
            "sh",
            &["-c", "sudo install -m 644 locale.conf /etc/locale.conf"]
        ));

        for locale in &self.locales {
            assert!(exec(
                "sh",
                &[
                    "-c",
                    format!(
                        "sudo sed -i 's/#{} UTF-8/{} UTF-8/g' /etc/locale.gen",
                        locale, locale
                    )
                    .as_str()
                ]
            ));
        }
        assert!(exec("sh", &["-c", "sudo locale-gen"]));
        self
    }

    ///
    ///
    /// # Panics
    ///
    /// if failed to remove file
    ///
    pub fn choose_packages(&mut self) -> &mut Self {
        if Path::new("/tmp/pkgs").exists() {
            self.packages.clear();
            assert!(self.packages.is_empty());
            loop {
                let p = MultiSelect::new("Select packages : ", parse_file_lines("/tmp/pkgs"))
                    .with_help_message("Packages to install on the system")
                    .prompt()
                    .expect("Failed to get packages");
                if p.is_empty() {
                    return self.choose_packages();
                }
                for x in &p {
                    self.packages.push(x.to_string());
                }

                match prompt_confirmation("Add package ? ") {
                    Ok(true) => continue,
                    Ok(false) | Err(_) => break,
                }
            }
            return self;
        }
        assert!(exec(
            "sh",
            &["-c", "sudo pacman -Sl core | cut -d ' ' -f 2 > pkgs"]
        ));
        assert!(exec(
            "sh",
            &["-c", "sudo pacman -Sl extra | cut -d ' ' -f 2 >> pkgs"]
        ));
        assert!(exec(
            "sh",
            &["-c", "sudo pacman -Sl multilib | cut -d ' ' -f 2 >> pkgs"]
        ));
        assert!(exec("sh", &["-c", "sudo pacman -Sg >> pkgs"]));
        assert!(exec("sh", &["-c", "yay -Sl aur | cut -d ' ' -f 2 >> pkgs"]));
        assert!(exec("sh", &["-c", "sudo install -m 644 pkgs /tmp/pkgs"]));
        assert!(exec("sh", &["-c", "rm pkgs"]));
        self.choose_packages()
    }

    ///
    /// # Panics
    ///
    fn configure_boot(&mut self) -> &mut Self {
        assert!(exec("sh", &["-c", "sudo mkdir -p /boot/grub"]));
        assert!(
            exec("sh", &["-c", "sudo grub-mkconfig -o /boot/grub/grub.cfg"]),
            "Failed to generate grub config"
        );
        assert!(exec("sh", &["-c", "sudo grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id arch --recheck"]),"Failed to install grub menu");
        self
    }

    ///
    /// # Panics
    ///
    pub fn create_users(&mut self) -> &mut Self {
        for user in &self.users {
            if user.sudoers {
                assert!(
                    exec(
                        "sh",
                        &[
                            "-c",
                            format!(
                                "sudo useradd -m -U -p {} {} -s {}",
                                user.password, user.name, user.shell
                            )
                            .as_str()
                        ]
                    ),
                    "Failed to create the new user"
                );
                assert!(
                    exec(
                        "sh",
                        &[
                            "-c",
                            format!(
                                "sudo echo '{} ALL=(ALL) ALL' > /etc/sudoers.d/{} ",
                                user.name, user.name
                            )
                            .as_str()
                        ]
                    ),
                    "Failed to create the new user"
                );
            } else {
                assert!(
                    exec(
                        "sh",
                        &[
                            "-c",
                            format!(
                                "sudo useradd -m -U -p {} {} -s {}",
                                user.password, user.name, user.shell
                            )
                            .as_str()
                        ]
                    ),
                    "Failed to create the new user"
                );
            }
        }
        self
    }

    ///
    /// # Panics
    ///
    pub fn run(&mut self) -> ExitCode {
        let run = Confirm::new("Run installation ? ")
            .with_default(true)
            .prompt()
            .unwrap();
        if run {
            return self
                .install_profile()
                .install_package()
                .create_users()
                .configure_timezone()
                .configure_locale()
                .configure_keymap()
                .configure_hostname()
                .systemd()
                .quit_installer();
        }
        install()
    }

    ///
    /// # Panics
    ///
    pub fn configure_users(&mut self) -> &mut Self {
        let create = match prompt_confirmation("Create a new user ? : ") {
            Ok(true) => true,
            Ok(false) | Err(_) => false,
        };
        if create {
            loop {
                let name = Text::new("New Username : ")
                    .with_help_message("New username")
                    .prompt()
                    .unwrap();
                let shell = Select::new(
                    format!("{name}'s shell : ").as_str(),
                    parse_file_lines("/etc/shells"),
                )
                .prompt()
                .unwrap();

                if !name.is_empty() {
                    let password = Password::new(format!("{name}'s password : ").as_str())
                        .prompt()
                        .unwrap();

                    let sudoers = match prompt_confirmation(
                        format!("{name}'s user can administrate the system : ").as_str(),
                    ) {
                        Ok(false) | Err(_) => false,
                        Ok(true) => true,
                    };
                    self.users.push(Users::new(
                        name.to_string(),
                        password.to_string(),
                        format!("/usr/bin/{shell}"),
                        sudoers,
                    ));
                    self.users_table.push(Users::new(
                        name.to_string(),
                        "********".to_string(),
                        shell.to_string(),
                        sudoers,
                    ));
                    match prompt_confirmation("Add a new user ?") {
                        Ok(true) => continue,
                        Ok(false) | Err(_) => break,
                    }
                }
            }
            return self;
        }
        self
    }

    ///
    /// # Panics
    ///
    pub fn choose_timezone(&mut self) -> &mut Self {
        let zone = Text::new("Please enter your timezone : ").prompt().unwrap();
        if zone.is_empty() {
            return self.choose_timezone();
        }
        self.timezone.clear();
        self.timezone.push_str(zone.as_str());
        self
    }

    ///
    /// # Panics
    ///
    pub fn configure_mirrors(&mut self) -> &mut Self {
        let country = Text::new("Please enter your country : ").prompt().unwrap();

        if country.is_empty() {
            return self.configure_mirrors();
        }
        let confirm_mirror = prompt_confirmation(
            format!("Set your mirrorlist to the {country} country : ").as_str(),
        );
        match confirm_mirror {
            Ok(false) | Err(_) => self.configure_mirrors(),
            Ok(true) => {
                assert!(exec(
            "sh",
            &[
                "-c",
                format!(
                    "sudo reflector --sort delay -c {country} --save /etc/pacman.d/mirrorlist -p https"
                )
                .as_str()
            ],
        ),"Failed to generate mirrorlist");
                assert!(exec(
            "sh",
            &[
                "-c",
                "sudo sed -i 's/#ParallelDownloads = 5/ParallelDownloads = 5/g' /etc/pacman.conf"
            ]
        ),"Failed to set Parallel download to 5");
                assert!(exec("sh", &["-c", "yay -Syyu"]), "Failed to update mirrors");
                self
            }
        }
    }

    ///
    /// # Panics
    ///
    pub fn configure_root(&mut self) -> &mut Self {
        let root = match prompt_confirmation("Enable root user ? ") {
            Ok(true) => true,
            Ok(false) | Err(_) => false,
        };
        if root {
            let password = Password::new("root's password : ").prompt().unwrap();
            assert!(self.root.insert(root, password).is_none());
        } else {
            assert!(self.root.insert(root, String::new()).is_none());
        }
        self
    }

    ///
    /// # Panics
    ///
    pub fn choose_profile(&mut self) -> &mut Self {
        let profile = Select::new(
            "Select a profile",
            vec!["@gnome", "@deepin", "@kde", "@i3", "@xmonad", "@none"],
        )
        .prompt()
        .unwrap();
        if profile.is_empty() {
            return self.choose_profile();
        }
        self.profile = profile.to_string();

        self.choose_packages()
    }

    ///
    /// # Panics
    ///
    pub fn configure_hostname(&mut self) -> &mut Self {
        assert!(
            exec(
                "sh",
                &["-c", format!("echo {} > hostname", self.hostname).as_str()],
            ),
            "Failed to define hostname"
        );

        assert!(
            exec("sh", &["-c", "sudo install -m 644 hostname /etc/hostname"],),
            "Failed to install hostname"
        );

        assert!(
            exec("sh", &["-c", "rm hostname"]),
            "Failed to remove tmp hostname file"
        );
        self
    }
    ///
    /// # Panics
    ///
    pub fn choose_hostname(&mut self) -> &mut Self {
        self.hostname.clear();
        let hostname = Text::new("Please enter your hostname : ").prompt().unwrap();
        if hostname.is_empty() {
            return self.choose_hostname();
        }
        self.hostname.push_str(hostname.as_str());
        self
    }

    ///
    /// # Panics
    ///
    pub fn confirm(&mut self) -> ExitCode {
        let ok_lang = prompt_confirmation(format!("Use lang : {}", self.lang).as_str()).unwrap();
        if !ok_lang {
            return self.choose_language().confirm();
        }
        let ok_locale =
            prompt_confirmation(format!("Use locales : {:?}", self.locales).as_str()).unwrap();
        if !ok_locale {
            return self.choose_locales().confirm();
        }
        let ok_timezone =
            prompt_confirmation(format!("Use timezone : {}", self.timezone).as_str()).unwrap();
        if !ok_timezone {
            return self.choose_timezone().confirm();
        }
        let ok_keymap =
            prompt_confirmation(format!("Use keymap : {}", self.keymap).as_str()).unwrap();
        if !ok_keymap {
            return self.choose_keymap().confirm();
        }
        let ok_hostname =
            prompt_confirmation(format!("Use hostname : {}", self.hostname).as_str()).unwrap();
        if !ok_hostname {
            return self.choose_hostname().confirm();
        }
        let ok_profile =
            prompt_confirmation(format!("Use profile : {}", self.profile).as_str()).unwrap();
        if !ok_profile {
            return self.choose_profile().confirm();
        }
        self.run()
    }

    ///
    /// # Panics
    ///
    pub fn upgrade(&mut self) -> ExitCode {
        assert!(
            exec("sh", &["-c", "yay -Syu && flatpak update"]),
            "Failed to update the system"
        );
        self.quit("Updated successfully")
    }

    ///
    /// # Panics
    ///
    pub fn upgrade_and_reboot(&mut self) -> ExitCode {
        assert!(
            exec("sh", &["-c", "yay -Syu && flatpak update"]),
            "Failed to update the system"
        );
        assert!(exec(
            "sh",
            &[
                "-c",
                "sudo shutdown -r +5 \"Save your work! This system will shut down in five minutes\""
            ]
        ),"Failed to program the reboot of your system");
        self.quit("Save your works ! Your computer will reboot after five minutes.")
    }

    ///
    /// # Panics
    ///
    pub fn cancel_reboot(&mut self) -> ExitCode {
        assert!(
            exec("sh", &["-c", "shutdown -c"]),
            "Cancelation of rhe reboot task has failed"
        );
        self.quit("The reboot has been canceled successfully")
    }

    ///
    /// # Panics
    ///
    pub fn check_update(&mut self) -> ExitCode {
        assert!(exec("sh", &["-c", "checkupdates"]), "System is up to date");
        self.quit("Run -> arch --update in order to update your system")
    }
    ///
    /// # Panics
    ///
    pub fn man(&mut self) -> &mut Self {
        assert!(
            exec("sh", &["-c", "w3m man.archlinux.org"]),
            "Failed to navigate on website"
        );
        self
    }
    ///
    /// # Panics
    ///
    pub fn aur(&mut self) -> &mut Self {
        assert!(
            exec("sh", &["-c", "w3m aur.archlinux.org"]),
            "Failed to navigate on aur website"
        );
        self
    }
    ///
    /// # Panics
    ///
    pub fn packages(&mut self) -> &mut Self {
        assert!(
            exec("sh", &["-c", "w3m archlinux.org/packages/"]),
            "Failed to navigate on arch website"
        );
        self
    }
    ///
    /// # Panics
    ///
    fn install_profile(&mut self) -> &mut Self {
        println!("{}", format!("using {}", self.profile).as_str());
        assert!(Command::new("wget")
            .arg("-q")
            .arg(
                format!(
                    "https://raw.githubusercontent.com/otechdo/arch/main/arch/profiles/{}",
                    self.profile
                )
                .as_str()
            )
            .current_dir(".")
            .spawn()
            .unwrap()
            .wait()
            .unwrap()
            .success());
        assert!(
            exec(
                "sh",
                &[
                    "-c",
                    format!(
                        "xargs -d '\n' -a {} yay --noconfirm --needed -Syu",
                        self.profile
                    )
                    .as_str()
                ]
            ),
            "{}",
            format!("failed to install {}", self.profile).as_str()
        );
        if self.profile.eq("@gnome") {
            assert!(
                exec("sh", &["-c", "sudo systemctl enable gdm"]),
                "Failed to enable gdm"
            );
        } else if self.profile.eq("@kde") {
            assert!(
                exec("sh", &["-c", "sudo systemctl enable sddm"]),
                "Failed to enable sddm"
            );
        } else if self.profile.eq("@deepin") || self.profile.eq("@xmonad") || self.profile.eq("@i3")
        {
            assert!(
                exec("sh", &["-c", "sudo systemctl enable lightdm"]),
                "Failed to enable lightdm"
            );
            if self.profile.eq("@xmonad") {
                assert!(
                            exec("sh", &["-c", "mkdir ~/.xmonad && wget -q https://raw.githubusercontent.com/otechdo/arch/main/arch/config/xmonad/xmonad.hs && mv xmonad.hs ~/.xmonad && touch ~/.xmonad/build && chmod +x ~/.xmonad/build && xmonad --recompile"]),
                            "Failed to configure xmonad"
                            );
            }
        }
        std::fs::remove_file(self.profile.clone()).expect("failed to profile file");
        self
    }

    ///
    /// # Panics
    ///
    pub fn download_update(&mut self) -> ExitCode {
        assert!(
            exec("sh", &["-c", "checkupdates -d"]),
            "System is up to date"
        );
        self.quit("Run -> arch --update in order to update your system")
    }

    ///
    /// # Panics
    ///
    pub fn refresh_cache(&mut self) -> ExitCode {
        assert!(exec(
            "sh",
            &["-c", "pacman -Sl core | cut -d ' ' -f 2 > pkgs"]
        ));
        assert!(exec(
            "sh",
            &["-c", "pacman -Sl extra | cut -d ' ' -f 2 >> pkgs"]
        ));
        assert!(exec(
            "sh",
            &["-c", "pacman -Sl multilib | cut -d ' ' -f 2 >> pkgs"]
        ));
        assert!(exec("sh", &["-c", "pacman -Sg >> pkgs"]));
        assert!(exec("sh", &["-c", "yay -Sl aur | cut -d ' ' -f 2 >> pkgs"]));
        assert!(exec("sh", &["-c", "install -m 644 pkgs /tmp/pkgs"]));
        assert!(exec("sh", &["-c", "rm pkgs"]));
        self.quit("Packages cache updated successfully")
    }
}

fn help() -> i32 {
    println!("arch setup                    : Configure a new arch\narch --help                   : Display help\narch --install-packages       : Install packages as inplicit\narch --install-dependencies   : Install packages as dependencies\narch --remove-packages        : Remove selected packages\narch --update-mirrors         : Update arch mirrors\narch --update                 : Update arch\narch --update-and-reboot      : Update arch and reboot after five minutes\narch --download-updates       : Download all updates\narch --check-updates          : Check and print all available updates\narch --cancel-reboot          : Cancel rebooting after five minutes");
    1
}

///
/// # Panics
///
fn install_packages(pkgs: &[String]) -> i32 {
    for pkg in pkgs {
        if pkg.contains("arch") || pkg.contains("-S") {
            continue;
        }
        assert!(
            exec("sh", &["-c", format!("yay -S --noconfirm {pkg}").as_str()]),
            "{}",
            format!("Failed to install the {pkg} package").as_str()
        );
        assert!(notifme::Notification::new()
            .app("arch")
            .summary(format!("{pkg} Installed").as_str())
            .body(format!("{pkg} has been installed successfully").as_str())
            .timeout(5)
            .send());
    }
    0
}

///
/// # Panics
///
fn remove_packages(pkgs: &[String]) -> i32 {
    for pkg in pkgs {
        if pkg.contains("arch") || pkg.contains("-R") {
            continue;
        }
        assert!(
            exec("sh", &["-c", format!("yay -Rns {pkg}").as_str()]),
            "{}",
            format!("Failed to install the {pkg} package").as_str()
        );
    }
    0
}

///
/// # Panics
///
fn install() -> ExitCode {
    Arch::new()
        .check_network()
        .news()
        .forums()
        .wiki()
        .configure_mirrors()
        .choose_language()
        .choose_locales()
        .choose_keymap()
        .choose_timezone()
        .choose_hostname()
        .choose_profile()
        .configure_users()
        .confirm()
}
fn main() -> ExitCode {
    let args: Vec<String> = args().collect();
    if args.len() >= 2 && args.get(1).expect("failed to get argument").eq("-S") {
        exit(install_packages(&args));
    }
    if args.len() >= 2 && args.get(1).expect("failed to get argument").eq("-R") {
        exit(remove_packages(&args));
    }

    if args.len() == 2 && args.get(1).expect("failed to get argument").eq("-a") {
        return Arch::new().aur().quit("Exit aur successfully");
    }

    if args.len() == 2 && args.get(1).expect("failed to get argument").eq("--man")
        || args.get(1).expect("failed to get argument").eq("-m")
    {
        return Arch::new().man().quit("Exit man successfully");
    }

    if args.len() == 2 && args.get(1).unwrap().eq("setup") {
        return install();
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--news") || args.get(1).unwrap().eq("-n") {
        return Arch::new().news().quit("News exit success");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--wiki") || args.get(1).unwrap().eq("-w") {
        return Arch::new().wiki().quit("Wiki exit success");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--man")
        || args.get(1).unwrap().eq("--woman")
        || args.get(1).unwrap().eq("-m")
    {
        return Arch::new().man().quit("Man exit success");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--forums") || args.get(1).unwrap().eq("-f") {
        return Arch::new().forums().quit("Forums exit success");
    }
    if args.len() == 2 && args.get(1).expect("failed to get argument").eq("-a")
        || args.get(1).unwrap().eq("--aur")
    {
        return Arch::new().aur().quit("Exit aur successfully");
    }

    if args.len() == 2 && args.get(1).unwrap().eq("--install") || args.get(1).unwrap().eq("-i") {
        return Arch::new()
            .choose_packages()
            .install_package()
            .quit("Packages installed success");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--install-dependencies") {
        return Arch::new()
            .choose_packages()
            .install_dependencies()
            .quit("Dependencies as been installed successfully");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--uninstall") {
        return Arch::new()
            .choose_packages()
            .remove_package()
            .quit("Packages has been removed successfully");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--update-mirrors") {
        return Arch::new()
            .check_network()
            .configure_mirrors()
            .quit("Mirrors has been updated successfully");
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--help") || args.get(1).unwrap().eq("-h") {
        let _ = help();
        exit(0);
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--update") {
        return Arch::new().upgrade();
    }

    if args.len() == 2 && args.get(1).unwrap().eq("--refresh-cache") {
        return Arch::new().refresh_cache();
    }
    if args.len() == 3 && args.get(1).unwrap().eq("--update") && args.get(2).unwrap().eq("-r") {
        return Arch::new().upgrade_and_reboot();
    }
    if args.len() == 3 && args.get(1).unwrap().eq("-r") && args.get(2).unwrap().eq("--update") {
        return Arch::new().upgrade_and_reboot();
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--update-and-reboot") {
        return Arch::new().upgrade_and_reboot();
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--check-updates") {
        return Arch::new().check_update();
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--download-updates") {
        return Arch::new().download_update();
    }
    if args.len() == 2 && args.get(1).unwrap().eq("--cancel-reboot") {
        return Arch::new().cancel_reboot();
    }
    exit(help());
}