summaryrefslogtreecommitdiff
path: root/static/thesiah.sh
blob: f72380d8ad0fe47ef6dc5408f1324f75fdef1b53 (plain)
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
#!/bin/sh

# Soomin's Auto Rice Boostrapping Script (THESIAH)
# by Soomin Im <si@thesiah.xyz>
# License: GNU GPLv3

### OPTIONS AND VARIABLES ###

progsfile="thesiah.xyz/progs.csv"
dotfilesrepo="https://github.com/TheSiahxyz/.dotfiles.git"
obsidianrepo="https://github.com/TheSiahxyz/Obsidian.git"
passwordrepo="https://github.com/TheSiahxyz/.password-store.git"
neetcoderepo="https://github.com/TheSiahxyz/neetcode.git"
webrepo="https://github.com/TheSiahxyz/THESIAH.git"
aurhelper="yay"
repobranch="master"
initsys="$(basename "$(readlink -f /sbin/init)" | sed 's/-init//g')"
export TERM=ansi

### FUNCTIONS ###

installpkg() {
  pacman --noconfirm --needed -S "$1" >/dev/null 2>&1
}

error() {
  # Log to stderr and exit with failure.
  printf "%s\n" "$1" >&2
  exit 1
}

welcomemsg() {
  whiptail --title "Welcome!" \
    --msgbox "Welcome to Soomin's Auto-Rice Bootstrapping Script!\\n\\nThis script will automatically install a fully-featured Linux desktop, which I use as my main machine.\\n\\n-Soomin" 10 60

  whiptail --title "Important Note!" --yes-button "All ready!" \
    --no-button "Return..." \
    --yesno "Be sure the computer you are using has current pacman updates and refreshed Arch keyrings.\\n\\nIf it does not, the installation of some programs might fail." 8 70
}

shcheck() {
  CURRENT_SHELL=$(readlink /bin/sh)
  whiptail --title "Checking system to start the installation!"
  if [ "${CURRENT_SHELL##*/}" = "dash" ]; then
    whiptail --infobox "/bin/sh is linked to dash. Switching to bash..." 10 60 3>&1 1>&2 2>&3 3>&1
    if command -v bash >/dev/null 2>&1; then
      sudo ln -sfT /bin/bash /bin/sh
      whiptail --infobox "/bin/sh is now linked to bash." 10 60 3>&1 1>&2 2>&3 3>&1
    else
      whiptail --infobox "bash is not installed on your system." 10 60 3>&1 1>&2 2>&3 3>&1
      exit 1
    fi
  fi
}

getuserandpass() {
  # Prompts user for new username an password.
  name=$(whiptail --inputbox "First, please enter a name for the user account." 10 60 3>&1 1>&2 2>&3 3>&1) || exit 1
  while ! echo "$name" | grep -q "^[a-z_][a-z0-9_-]*$"; do
    name=$(whiptail --nocancel --inputbox "Username not valid. Give a username beginning with a letter, with only lowercase letters, - or _." 10 60 3>&1 1>&2 2>&3 3>&1)
  done
  pass1=$(whiptail --nocancel --passwordbox "Enter a password for that user." 10 60 3>&1 1>&2 2>&3 3>&1)
  pass2=$(whiptail --nocancel --passwordbox "Retype password." 10 60 3>&1 1>&2 2>&3 3>&1)
  while ! [ "$pass1" = "$pass2" ]; do
    unset pass2
    pass1=$(whiptail --nocancel --passwordbox "Passwords do not match.\\n\\nEnter password again." 10 60 3>&1 1>&2 2>&3 3>&1)
    pass2=$(whiptail --nocancel --passwordbox "Retype password." 10 60 3>&1 1>&2 2>&3 3>&1)
  done
  epass1=$(whiptail --nocancel --passwordbox "Enter a password for ecryptfs which will be used to set up an encrypt folder." 10 60 3>&1 1>&2 2>&3 3>&1)
  epass2=$(whiptail --nocancel --passwordbox "Retype password." 10 60 3>&1 1>&2 2>&3 3>&1)
  while ! [ "$epass1" = "$epass2" ]; do
    unset epass2
    epass1=$(whiptail --nocancel --passwordbox "Passwords do not match.\\n\\nEnter password again." 10 60 3>&1 1>&2 2>&3 3>&1)
    epass2=$(whiptail --nocancel --passwordbox "Retype password." 10 60 3>&1 1>&2 2>&3 3>&1)
  done
}

repocheck() {
  putrepo=$(whiptail --inputbox "Do you want to clone TheSiahxyz's repositories? y/n" 10 60 3>&1 1>&2 2>&3 3>&1) || exit 1
  while [ "$putrepo" != "y" ] && [ "$putrepo" != "n" ]; do
    putrepo=$(whiptail --inputbox "Invalid option! Choose 'y' or 'n'.\nDo you want to clone TheSiahxyz's repositories? y/n" 10 60 3>&1 1>&2 2>&3 3>&1) || exit 1
  done
}

usercheck() {
  ! { id -u "$name" >/dev/null 2>&1; } ||
    whiptail --title "WARNING" --yes-button "CONTINUE" \
      --no-button "No wait..." \
      --yesno "The user \`$name\` already exists on this system. SI can install for a user already existing, but it will OVERWRITE any conflicting settings/dotfiles on the user account.\\n\\nSI will NOT overwrite your user files, documents, videos, etc., so don't worry about that, but only click <CONTINUE> if you don't mind your settings being overwritten.\\n\\nNote also that SI will change $name's password to the one you just gave." 14 70
}

preinstallmsg() {
  whiptail --title "Let's get this party started!" --yes-button "Let's go!" \
    --no-button "No, nevermind!" \
    --yesno "The rest of the installation will now be totally automated, so you can sit back and relax.\\n\\nIt will take some time, but when done, you can relax even more with your complete system.\\n\\nNow just press <Let's go!> and the system will begin installation!" 13 60 || {
    clear
    exit 1
  }
}

adduserandpass() {
  # Adds user `$name` with password $pass1.
  whiptail --infobox "Adding user \"$name\"..." 7 50
  useradd -m -g wheel -G storage,power,video,audio -s /bin/zsh "$name" >/dev/null 2>&1 ||
    usermod -a -G wheel,storage,power,video,audio "$name" && mkdir -p \
    "/home/$name/.config" \
    "/home/$name/.local/bin" \
    "/home/$name/.local/share/history" \
    "/home/$name/.local/share/wallpapers" \
    "/home/$name/.local/src" \
    "/home/$name/Desktop" \
    "/home/$name/Documents" \
    "/home/$name/Downloads" \
    "/home/$name/Music" \
    "/home/$name/Pictures" \
    "/home/$name/Private/repos" \
    "/home/$name/Public" \
    "/home/$name/Torrents/complete" \
    "/home/$name/Torrents/incomplete" \
    "/media/$name/flash" \
    "/mnt/second" \
    "/home/$name" && echo "This is a private folder." >"/home/$name/Private/README.md" && chown -R "$name":wheel /home/"$name"
  export repodir="/home/$name/.local/src"
  mkdir -p "$repodir"
  chown -R "$name":wheel "$(dirname "$repodir")"
  echo "$name:$pass1" | chpasswd
}

refreshkeys() {
  case "$(readlink -f /sbin/init)" in
  *systemd*)
    whiptail --infobox "Refreshing Arch Keyring..." 7 40
    pacman --noconfirm -S archlinux-keyring >/dev/null 2>&1
    installpkg arch-install-scripts
    ;;
  *)
    whiptail --infobox "Enabling Arch Repositories for more a more extensive software collection..." 7 40
    pacman --noconfirm --needed -S \
      artix-keyring artix-archlinux-support >/dev/null 2>&1
    grep -q "^\[extra\]" /etc/pacman.conf ||
      printf '[extra]
Include = /etc/pacman.d/mirrorlist-arch

[multilib]
Include = /etc/pacman.d/mirrorlist-arch' >>/etc/pacman.conf
    pacman -Sy --noconfirm >/dev/null 2>&1
    pacman-key --populate archlinux >/dev/null 2>&1
    installpkg artools-base
    ;;
  esac
}

manualinstall() {
  # Installs $1 manually. Used only for AUR helper here.
  # Should be run after repodir is created and var is set.
  pacman -Qq "$1" && return 0
  whiptail --infobox "Installing \"$1\" manually." 7 50
  sudo -u "$name" mkdir -p "$repodir/$1"
  sudo -u "$name" git -C "$repodir" clone --depth 1 --single-branch \
    --no-tags -q "https://aur.archlinux.org/$1.git" "$repodir/$1" >/dev/null 2>&1 ||
    {
      cd "$repodir/$1" || return 1
      sudo -u "$name" git pull --force origin master >/dev/null 2>&1
    }
  cd "$repodir/$1" || exit 1
  sudo -u "$name" sh -c "cd '$repodir/$1' && makepkg --noconfirm -si >/dev/null 2>&1" || exit 1
}

maininstall() {
  # Installs all needed programs from master repo.
  whiptail --title "SI Installation" --infobox "Installing \`$1\` ($n of $total). $1 $2" 9 70
  installpkg "$1"
}

gitmakeinstall() {
  progname="${1##*/}"
  progname="${progname%.git}"
  dir="$repodir/$progname"
  whiptail --title "SI Installation" \
    --infobox "Installing \`$progname\` ($n of $total) via \`git\` and \`make\`. $(basename "$1") $2" 8 70
  sudo -u "$name" git -C "$repodir" clone --depth 1 --single-branch \
    --no-tags -q "$1" "$dir" ||
    {
      cd "$dir" || return 1
      sudo -u "$name" git pull --force origin master
    }
  # Check the repository name and act accordingly for suckless
  case "$progname" in
  "suckless")
    for sub in "${dir}/"*; do
      cd "$sub" || continue
      make >/dev/null 2>&1
      make install >/dev/null 2>&1
    done
    ;;
  *)
    cd "$dir" || exit 1
    make >/dev/null 2>&1
    make install >/dev/null 2>&1
    ;;
  esac
  cd /tmp || return 1
}

aurinstall() {
  whiptail --title "SI Installation" \
    --infobox "Installing \`$1\` ($n of $total) from the AUR. $1 $2" 9 70
  echo "$aurinstalled" | grep -q "^$1$"
  sudo -u "$name" $aurhelper -S --noconfirm "$1" >/dev/null 2>&1
}

pipinstall() {
  whiptail --title "SI Installation" \
    --infobox "Installing the Python package \`$1\` ($n of $total). $1 $2" 9 70
  [ -x "$(command -v "pip")" ] || installpkg python-pip >/dev/null 2>&1
  yes | pip install "$1" >/dev/null 2>&1
}

pipxinstall() {
  whiptail --title "SI Installation" \
    --infobox "Installing the Python package \`$1\` ($n of $total). $1 $2" 9 70
  [ -x "$(command -v "pipx")" ] || installpkg python-pipx >/dev/null 2>&1
  yes | pipx install "$1" >/dev/null 2>&1
}

# runit
initinstall() {
  initpkg="$1-$initsys"
  whiptail --title "SI Installation" \
    --infobox "Installing the package \`$1\` and the corresponding init package \'$initpkg'\ ($n of $total). $1 $initpkg $2" 9 70
  installpkg "$1" && installpkg "$1-$initsys" || error "Failed to install package $1 and init package $initpkg"
}

installationloop() {
  ([ -f "$progsfile" ] && cp "$progsfile" /tmp/progs.csv) ||
    curl -Ls "$progsfile" | sed '/^#/d' >/tmp/progs.csv
  total=$(wc -l </tmp/progs.csv)
  aurinstalled=$(pacman -Qqm)
  while IFS=, read -r tag program comment; do
    n=$((n + 1))
    echo "$comment" | grep -q "^\".*\"$" &&
      comment="$(echo "$comment" | sed -E "s/(^\"|\"$)//g")"
    case "$tag" in
    "A") aurinstall "$program" "$comment" ;;
    "I")
      case "$(readlink -f /sbin/init)" in
      *systemd*) maininstall "$program" "$comment" ;;
      *) initinstall "$program" "$comment" ;;
      esac
      ;;
    "G") gitmakeinstall "$program" "$comment" ;;
    "P") pipinstall "$program" "$comment" ;;
    "X") pipxinstall "$program" "$comment" ;;
    *) maininstall "$program" "$comment" ;;
    esac
  done </tmp/progs.csv
}

putgitrepo() {
  # Downloads a gitrepo $1 and places the files in $2 only overwriting conflicts
  whiptail --infobox "Downloading and installing config files..." 7 60
  [ -z "$3" ] && branch="master" || branch="$repobranch"
  dir=$(mktemp -d)
  [ ! -d "$2" ] && mkdir -p "$2"
  chown "$name":wheel "$dir" "$2"
  sudo -u "$name" git -C "$repodir" clone --depth 1 \
    --single-branch --no-tags -q --recursive -b "$branch" \
    --recurse-submodules "$1" "$dir"
  sudo -u "$name" cp -rfT "$dir" "$2"
}

vimplugininstall() {
  # Installs vim plugins.
  whiptail --infobox "Installing vim plugins..." 7 60
  mkdir -p "/home/$name/.config/vim/autoload"
  curl -Ls "https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim" >"/home/$name/.config/vim/autoload/plug.vim"
  chown -R "$name:wheel" "/home/$name/.config/vim"
  NVIM_APPNAME=TheSiahxyz nvim --headless "+Lazy! sync" +qa
}

makeuserjs() {
  # Get the Arkenfox user.js and prepare it.
  arkenfox="$sipdir/arkenfox.js"
  overrides="$sipdir/user-overrides.js"
  userjs="$sipdir/user.js"
  ln -fs "/home/$name/.config/firefox/thesiah.js" "$overrides"
  [ ! -f "$arkenfox" ] && curl -sL "https://raw.githubusercontent.com/arkenfox/user.js/master/user.js" >"$arkenfox"
  chown "$name:wheel" "$arkenfox" "$userjs"
  cat "$arkenfox" "$overrides" >"$userjs"
  # Install the updating script.
  mkdir -p /usr/local/lib /etc/pacman.d/hooks
  cp "/home/$name/.local/bin/arkenfox-auto-update" /usr/local/lib/
  chown root:root /usr/local/lib/arkenfox-auto-update
  chmod 755 /usr/local/lib/arkenfox-auto-update
  # Trigger the update when needed via a pacman hook.
  printf '[Trigger]
Operation = Upgrade
Type = Package
Target = firefox
Target = librewolf-bin
Target = librewolf
[Action]
Description=Update Arkenfox user.js
When=PostTransaction
Depends=arkenfox-user.js
Exec=/usr/local/lib/arkenfox-auto-update' >/etc/pacman.d/hooks/arkenfox.hook
}

installffaddons() {
  addonlist="ublock-origin decentraleyes istilldontcareaboutcookies vimium-ff sponsorblock enhancerforyouTube adblock-plus languagetool darkreader livemarks traduzir-paginas-web video-downloadhelper passff"
  addontmp="$(mktemp -d)"
  trap 'rm -rf "$addontmp"' HUP INT QUIT TERM PWR EXIT
  IFS=' '
  sudo -u "$name" mkdir -p "$sipdir/extensions/"
  for addon in $addonlist; do
    if [ "$addon" = "ublock-origin" ]; then
      addonurl="$(curl -sL https://api.github.com/repos/gorhill/uBlock/releases/latest | grep -E 'browser_download_url.*\.firefox\..*xpi' | cut -d '"' -f 4)"
    else
      addonurl="$(curl -s "https://addons.mozilla.org/en-US/firefox/addon/${addon}/" | grep -o 'https://addons.mozilla.org/firefox/downloads/file/[^"]*')"
    fi
    file="${addonurl##*/}"
    sudo -u "$name" curl -LOs "$addonurl" >"$addontmp/$file"
    id="$(unzip -p "$file" manifest.json | grep "\"id\"")"
    id="${id%\"*}"
    id="${id##*\"}"
    mv "$file" "$sipdir/extensions/$id.xpi"
  done
  chown -R "$name:$name" "$sipdir/extensions"
}

librewolfsetup() {
  whiptail --infobox "Setting browser privacy settings and add-ons..." 7 60

  browserdir="/home/$name/.librewolf"
  profilesini="$browserdir/profiles.ini"

  sudo -u "$name" librewolf --headless >/dev/null 2>&1 &
  sleep 1
  profile="$(sed -En '/Default=.*\.default-(default|release)/s/.*=//p' "$profilesini")"
  pdir="$browserdir/$profile"
  siprofile="si.default"
  sipdir="$browserdir/$siprofile"

  if [ -d "$pdir" ]; then
    mv "$pdir" "$sipdir"
    sed -i "s/$profile/$siprofile/g" "$profilesini"

    makeuserjs
    installffaddons
  else
    error "User exited."
  fi

  pkill -u "$name" librewolf
}

addsudo() {
  echo "%wheel ALL=(ALL:ALL) ALL" >/etc/sudoers.d/00-thesiah-wheel-can-sudo
  echo "%wheel ALL=(ALL:ALL) NOPASSWD: /usr/bin/shutdown,/usr/bin/reboot,/usr/bin/systemctl suspend,/usr/bin/wifi-menu,/usr/bin/mount,/usr/bin/umount,/usr/bin/lsblk,/usr/bin/pacman -Syu,/usr/bin/pacman -Syyu,/usr/bin/pacman -Syyu --noconfirm,/usr/bin/loadkeys,/usr/bin/pacman -Syyuw --noconfirm,/usr/bin/pacman -S -y --config /etc/pacman.conf --,/usr/bin/pacman -S -y -u --config /etc/pacman.conf --,/usr/bin/cat" >/etc/sudoers.d/01-thesiah-cmds-without-password
  echo "Defaults editor=/usr/bin/nvim" >/etc/sudoers.d/02-thesiah-visudo-editor
  mkdir -p /etc/sysctl.d
  echo "kernel.dmesg_restrict = 0" >/etc/sysctl.d/dmesg.conf

  # Cleanup
  rm -f /etc/sudoers.d/thesiah-temp
}

pamgnupg() {
  whiptail --infobox "Setting up pam-gnupg..." 7 50
  $aurhelper -Qq pam-gnupg >/dev/null 2>&1 || aurinstall pam-gnupg
  pacman -Qq pam_mount >/dev/null 2>&1 || installpkg pam_mount
  sleep 3
  grep -Eq "auth\s+optional\s+pam_gnupg.so store-only" /etc/pam.d/system-local-login || echo "auth      optional  pam_gnupg.so store-only" >>/etc/pam.d/system-local-login
  grep -Eq "session\s+optional\s+pam_gnupg.so" /etc/pam.d/system-local-login || echo "session   optional  pam_gnupg.so" >>/etc/pam.d/system-local-login
  grep -Eq "auth\s+optional\s+pam_mount.so" /etc/pam.d/system-login || sed -i "/auth       requisite  pam_nologin.so/a auth       optional   pam_mount.so" /etc/pam.d/system-login
  grep -Eq "password\s+optional\s+pam_mount.so" /etc/pam.d/system-login || sed -i "/password   include    system-auth/i password   optional   pam_mount.so " /etc/pam.d/system-login
  grep -Eq "session\s+\[success=1 default=ignore\]\s+pam_succeed_if.so\s+service = systemd-user quiet" /etc/pam.d/system-login || sed -i "/session    optional   pam_keyinit.so       force revoke/a session [success=1 default=ignore]  pam_succeed_if.so  service = systemd-user quiet\nsession    optional   pam_mount.so" /etc/pam.d/system-login
}

ecryptfssetup() {
  whiptail --infobox "Setting up ecryptfs..." 7 50
  [ -x "$(command -v "ecryptfs")" ] || installpkg ecryptfs-utils
  [ -d "/home/$name/.secret" ] || mkdir -p "/home/$name/.secret"
  [ -d "/home/$name/Private" ] || mkdir -p "/home/$name/Private"
  chown "$name":wheel "/home/$name/.secret"
  chown "$name":wheel "/home/$name/Private"

  # Ecrypt the folder
  [ -d /root/.ecryptfs ] && rm -rf /root/.ecryptfs
  sleep 1
  printf '\nyes\nyes\n' | mount -t ecryptfs /home/"$name"/.secret /home/"$name"/Private -o ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,passphrase_passwd="$epass1",ecryptfs_cipher=aes,ecryptfs_key_bytes=32 >/dev/null 2>&1
  sleep 1
  umount /home/"$name"/Private >/dev/null 2>&1
  sleep 1
}

ufwsetup() {
  whiptail --infobox "Setting up ufw..." 7 50
  [ -x "$(command -v "ufw")" ] || installpkg ufw
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq ufw-"$initsys" >/dev/null 2>&1 || installpkg ufw-"$initsys"
  }
  sleep 1
  ufw --force reload >/dev/null 2>&1
  ufw default deny incoming >/dev/null 2>&1
  ufw allow 80 >/dev/null 2>&1
  ufw allow 443 >/dev/null 2>&1
  ufw allow 25/tcp >/dev/null 2>&1
  ufw allow 587/tcp >/dev/null 2>&1
  ufw allow 3478/udp >/dev/null 2>&1
  ufw allow 5349/tcp >/dev/null 2>&1
  ufw allow 10000/udp >/dev/null 2>&1
  ufw allow in ssh >/dev/null 2>&1
  ufw allow in IMAPS >/dev/null 2>&1
  ufw allow in POP3 >/dev/null 2>&1
  ufw allow in SMTP >/dev/null 2>&1
  ufw allow in 'WWW Full' >/dev/null 2>&1
  ufw allow in 'Postfix SMTPS' >/dev/null 2>&1
  ufw allow in 'Mail Submission' >/dev/null 2>&1
  ufw --force reload >/dev/null 2>&1
  sleep 1
  case "$initsys" in
  "runit")
    ln -sf /etc/runit/sv/ufw /run/runit/service/ >/dev/null 2>&1
    sleep 1
    sv start ufw >/dev/null 2>&1 || sv force-restart ufw >/dev/null 2>&1
    ;;
  "openrc")
    rc-update add ufw default >/dev/null 2>&1
    sleep 1
    rc-service ufw start >/dev/null 2>&1
    ;;
  "s6")
    ln -sf /etc/s6/sv/ufw /run/s6/services/ >/dev/null 2>&1
    sleep 1
    s6-svc -u /run/s6/services/ufw >/dev/null 2>&1
    ;;
  "systemd")
    systemctl restart ufw
    ;;
  esac
}

sambasetup() {
  whiptail --infobox "Setting up samba..." 7 50
  [ -x "$(command -v "samba")" ] || installpkg samba
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq samba-"$initsys" >/dev/null 2>&1 || installpkg samba-"$initsys"
  }
  sleep 1
  ufw allow 137/tcp >/dev/null 2>&1
  ufw allow 137/udp >/dev/null 2>&1
  ufw allow 138/tcp >/dev/null 2>&1
  ufw allow 138/udp >/dev/null 2>&1
  ufw allow 139/tcp >/dev/null 2>&1
  ufw allow 445/tcp >/dev/null 2>&1
  ufw --force reload >/dev/null 2>&1
  [ -f /etc/samba/smb.conf ] || touch /etc/samba/smb.conf
  sleep 1
  printf "$pass1" | smbpasswd -a "$name" >/dev/null 2>&1
  sleep 1
  case "$initsys" in
  "runit")
    ln -sf /etc/runit/sv/smbd /run/runit/service/ >/dev/null 2>&1
    ln -sf /etc/runit/sv/nmbd /run/runit/service/ >/dev/null 2>&1
    sleep 1
    sv start smbd >/dev/null 2>&1 || sv force-restart smbd >/dev/null 2>&1
    sv start nmbd >/dev/null 2>&1 || sv force-restart nmbd >/dev/null 2>&1
    ;;
  "openrc")
    rc-update add samba default >/dev/null 2>&1
    sleep 1
    rc-service samba start >/dev/null 2>&1
    ;;
  "s6")
    ln -sf /etc/s6/sv/smbd /run/s6/services/ >/dev/null 2>&1
    ln -sf /etc/s6/sv/nmbd /run/s6/services/ >/dev/null 2>&1
    sleep 1
    s6-svc -u /run/s6/services/smbd >/dev/null 2>&1
    s6-svc -u /run/s6/services/nmbd >/dev/null 2>&1
    ;;
  "systemd")
    systemctl restart smbd
    systemctl restart nmbd
    ;;
  esac
}

bluezsetup() {
  whiptail --infobox "Setting up bluetooth..." 7 50
  pacman -Qq bluez >/dev/null 2>&1 || installpkg bluez
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq bluez-"$initsys" >/dev/null 2>&1 || installpkg bluez-"$initsys"
  }
  sleep 3
  case "$initsys" in
  "runit")
    ln -sf /etc/runit/sv/bluetoothd /run/runit/service/ >/dev/null 2>&1
    sleep 1
    sv start bluetoothd >/dev/null 2>&1 || sv force-restart bluetoothd >/dev/null 2>&1
    ;;
  "openrc")
    rc-update add bluetoothd default >/dev/null 2>&1
    sleep 1
    rc-service bluetoothd start >/dev/null 2>&1
    ;;
  "s6")
    ln -sf /etc/s6/sv/bluetoothd /run/s6/services/ >/dev/null 2>&1
    sleep 1
    s6-svc -u /run/s6/services/bluetoothd >/dev/null 2>&1
    ;;
  "systemd")
    systemctl restart bluetooth
    ;;
  esac
}

cronsetup() {
  whiptail --infobox "Setting up cronjob..." 7 50
  pacman -Qq cronie >/dev/null 2>&1 || installpkg cronie
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq cronie-"$initsys" >/dev/null 2>&1 || installpkg cronie-"$initsys"
  }
  sleep 1
  [ -f "${XDG_CONFIG_HOME:-$HOME/.config}"/crons ] &&
    crontab -u "$name" - <"${XDG_CONFIG_HOME:-$HOME/.config}"/crons &&
    rm "${XDG_CONFIG_HOME:-$HOME/.config}"/crons
  sleep 3
  case "$initsys" in
  "runit")
    ln -sf /etc/runit/sv/cronie /run/runit/service/ >/dev/null 2>&1
    sleep 1
    sv start cronie >/dev/null 2>&1 || sv force-restart cronie >/dev/null 2>&1
    ;;
  "openrc")
    rc-update add cronie default >/dev/null 2>&1
    sleep 1
    rc-service cronie start >/dev/null 2>&1
    ;;
  "s6")
    ln -sf /etc/s6/sv/cronie /run/s6/services/ >/dev/null 2>&1
    sleep 1
    s6-svc -u /run/s6/services/cronie >/dev/null 2>&1
    ;;
  "systemd")
    systemctl restart cronie
    ;;
  esac
}

tlpsetup() {
  whiptail --infobox "Setting up tlp..." 7 50
  [ -x "$(command -v "tlp")" ] || installpkg tlp
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq tlp-"$initsys" >/dev/null 2>&1 || installpkg tlp-"$initsys"
  }
  sleep 1
  printf 'TLP_DEFAULT_MODE=AC
START_CHARGE_THRESH_BAT0=20
STOP_CHARGE_THRESH_BAT0=80
START_CHARGE_THRESH_BAT1=50
STOP_CHARGE_THRESH_BAT1=75' >/etc/tlp.d/01-battery.conf 2>/dev/null
  echo 'USB_AUTOSUSPEND=0' >/etc/tlp.d/02-usb.conf 2>/dev/null
  case "$initsys" in
  "runit")
    ln -sf /etc/runit/sv/tlp /run/runit/service/ >/dev/null 2>&1
    sleep 1
    sv start tlp >/dev/null 2>&1 || sv force-restart tlp >/dev/null 2>&1
    ;;
  "openrc")
    rc-update add tlp default >/dev/null 2>&1
    sleep 1
    rc-service tlp start >/dev/null 2>&1
    ;;
  "s6")
    ln -sf /etc/s6/sv/tlp /run/s6/services/ >/dev/null 2>&1
    sleep 1
    s6-svc -u /run/s6/services/tlp >/dev/null 2>&1
    ;;
  "systemd")
    systemctl restart tlp
    ;;
  esac
  tlp start >/dev/null 2>&1
}

bbswitchsetup() {
  whiptail --infobox "Setting up bbswitch..." 7 50
  pacman -Qq bbswitch >/dev/null 2>&1 || installpkg bbswitch
  sleep 1
  echo 'bbswitch' >/etc/modules-load.d/bbswitch.conf >/dev/null 2>&1
  echo 'options bbswitch load_state=0 unload_state=1' >/etc/modprobe.d/bbswitch.conf >/dev/null 2>&1
  echo 'RUNTIME_PM_DRIVER_DENYLIST="nouveau nvidia"' >/etc/tlp.d/03-driver.conf 2>/dev/null
}

sshsetup() {
  whiptail --infobox "Setting up ssh..." 7 50
  [ -x "$(command -v "ssh")" ] || installpkg openssh
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq openssh-"$initsys" >/dev/null 2>&1 || installpkg openssh-"$initsys"
  }
  sleep 1
  sed -Ei "s/^#?(PasswordAuthentication).*/\1 no/;s/^#?(UsePAM).*/\1 no/" /etc/ssh/sshd_config
  case "$initsys" in
  "runit")
    ln -sf /etc/runit/sv/sshd /run/runit/service/ >/dev/null 2>&1
    sleep 1
    sv start sshd >/dev/null 2>&1 || sv force-restart sshd >/dev/null 2>&1
    ;;
  "openrc")
    rc-update add sshd default >/dev/null 2>&1
    sleep 1
    rc-service sshd start >/dev/null 2>&1
    ;;
  "s6")
    ln -sf /etc/s6/sv/sshd /run/s6/services/ >/dev/null 2>&1
    sleep 1
    s6-svc -u /run/s6/services/sshd >/dev/null 2>&1
    ;;
  "systemd")
    systemctl restart sshd
    ;;
  esac
}

vpnsetup() {
  whiptail --infobox "Setting up vpn..." 7 50
  [ -x "$(command -v "openvpn")" ] || installpkg openvpn
  [ ! "$initsys" = "systemd" ] && {
    pacman -Qq openvpn-"$initsys" >/dev/null 2>&1 || installpkg openvpn-"$initsys"
  }
  pacman -Qq networkmanager-openvpn >/dev/null 2>&1 || installpkg networkmanager-openvpn
  sleep 3
  nmcli connection import type openvpn file /home/"$name"/.dotfiles/ar/.config/openvpn/thesiah.ovpn >/dev/null 2>&1
}

elogindsetup() {
  [ -d /etc/elogind/logind.conf.d ] || mkdir -p /etc/elogind/logind.conf.d 2>/dev/null
  printf '[Login]
HandleLidSwitch=ignore
HandleLidSwitchExternalPower=ignore
HandleLidSwitchDocked=ignore
LidSwitchIgnoreInhibited=no' >/etc/elogind/logind.conf.d/00-lid.conf 2>/dev/null
  ln -sf /etc/runit/sv/elogind /run/runit/service/
  sleep 1
  sv start elogind >/dev/null 2>&1 || sv force-restart elogind >/dev/null 2>&1
}

microsetup() {
  microinfo=$(lspci | grep -E "VGA|Display")
  if echo "$microinfo" | grep -qi "Intel"; then
    installpkg xf86-video-intel
    installpkg intel-ucode
  elif echo "$microinfo" | grep -qi "AMD"; then
    installpkg xf86-video-amdgpu
    installpkg amd-ucode
  fi
}

dashsetup() {
  whiptail --infobox "Setting shell to dash..." 7 50
  [ -x "$(command -v "dash")" ] || installpkg dash
  printf '[Trigger]
Type = Package
Operation = Install
Operation = Upgrade
Target = bash

[Action]
Description = Re-pointing /bin/sh symlink to dash...
When = PostTransaction
Exec = /usr/bin/ln -sfT dash /usr/bin/sh
Depends = dash' >/usr/share/libalpm/hooks/relinking-dash.hook
  sleep 1
  ln -sfT dash /usr/bin/sh
}

finalize() {
  unset pass1 pass2
  unset epass1 epass2
  sudo -u "$name" ln -sf /home/"$name"/.dotfiles/default/Pictures/wallpaper/city.png /home/"$name"/.local/share/wallpapers/bg
  # Farewell
  whiptail --title "All done!" \
    --msgbox "Congrats! Provided there were no hidden errors, the script completed successfully and all the programs and configuration files should be in place.\\n\\nTo run the new graphical environment, log out and log back in as your new user, then run the command \"startx\" to start the graphical environment (it will start automatically in tty1).\\n\\n.t Soomin" 13 80
}

### THE ACTUAL SCRIPT ###

### This is how everything happens in an intuitive format and order.

# Check if user is root on Arch distro. Install whiptail.
pacman --noconfirm --needed -Sy libnewt ||
  error "Are you sure you're running this as the root user, are on an Arch-based distribution and have an internet connection?"

# Welcome user and pick dotfiles.
welcomemsg || error "User exited."

# Check the default shell.
shcheck || error "User exited."

# Get and verify username and password.
getuserandpass || error "User exited."

# Decide cloning repositories.
[ "$name" = "si" ] && {
  repocheck || error "User exited."
}

# Give warning if user already exists.
usercheck || error "User exited."

# Last chance for user to back out before install.
preinstallmsg || error "User exited."

### The rest of the script requires no user input.

# Refresh Arch keyrings.
refreshkeys ||
  error "Error automatically refreshing Arch keyring. Consider doing so manually."

for x in curl ca-certificates base-devel git ntp zsh stow; do
  whiptail --title "SI Installation" \
    --infobox "Installing \`$x\` which is required to install and configure other programs." 8 70
  installpkg "$x"
done

whiptail --title "SI Installation" \
  --infobox "Synchronizing system time to ensure successful and secure installation of software..." 8 70
ntpd -q -g >/dev/null 2>&1

adduserandpass || error "Error adding username and/or password."

[ -f /etc/sudoers.pacnew ] && cp /etc/sudoers.pacnew /etc/sudoers # Just in case

# Allow user to run sudo without password. Since AUR programs must be installed
# in a fakeroot environment, this is required for all builds with AUR.
trap 'rm -f /etc/sudoers.d/thesiah-temp' HUP INT QUIT TERM PWR EXIT
echo "%wheel ALL=(ALL) NOPASSWD: ALL
Defaults:%wheel,root runcwd=*" >/etc/sudoers.d/thesiah-temp

# Make pacman colorful, concurrent downloads and Pacman eye-candy.
grep -q "ILoveCandy" /etc/pacman.conf || sed -i "/#VerbosePkgLists/a ILoveCandy" /etc/pacman.conf
sed -Ei "s/^#(ParallelDownloads).*/\1 = 5/;/^#Color$/s/#//" /etc/pacman.conf
# sed -i "/^#\[lib32\]/, /^#Include = \/etc\/pacman\.d\/mirrorlist$/ s/^#//" /etc/pacman.conf

# Use all cores for compilation.
sed -i "s/-j2/-j$(nproc)/;/^#MAKEFLAGS/s/^#//" /etc/makepkg.conf

pacman -Sy --noconfirm >/dev/null 2>&1

manualinstall $aurhelper || error "Failed to install AUR helper."

# Make sure .*-git AUR packages get updated automatically.
$aurhelper -Y --save --devel

# The command that does all the installing. Reads the progs.csv file and
# installs each needed program the way required. Be sure to run this only after
# the user has been created and has priviledges to run sudo without a password
# and all build dependencies are installed.
installationloop

# Install the dotfiles in the user's home directory, but remove .git dir and
# other unnecessary files.
putgitrepo "$dotfilesrepo" "/home/$name/.dotfiles" "$repobranch"
rm -rf "/home/$name/.git/" "/home/$name/README.md" "/home/$name/LICENSE" "/home/$name/FUNDING.yml"
find /home/"$name" -maxdepth 1 -type f -name ".*" -exec rm -rf {} \;
cd "/home/$name/.dotfiles" && sudo -u "$name" stow --no-folding -S ar && sudo -u "$name" stow --no-folding -S global && cd /tmp || exit 1

# Link profiles
sudo -u "$name" ln -sf "/home/$name/.dotfiles/ar/.config/shell/profile" "/home/$name/.zprofile"
sudo -u "$name" ln -sf "/home/$name/.dotfiles/ar/.config/x11/xprofile" "/home/$name/.xprofile"
sudo -u "$name" ln -sf "/home/$name/.dotfiles/ar/.config/bash/bash_profile" "/home/$name/.bash_profile"
sudo -u "$name" ln -sf "/home/$name/.dotfiles/ar/.config/bash/bashrc" "/home/$name/.bashrc"

# Install vim plugins if not alread present.
[ ! -f "/home/$name/.config/vim/autoload/plug.vim" ] && vimplugininstall

# Most important command! Get rid of the beep!
rmmod pcspkr
echo "blacklist pcspkr" >/etc/modprobe.d/nobeep.conf

# Make zsh the default shell for the user.
chsh -s /bin/zsh "$name" >/dev/null 2>&1
sudo -u "$name" mkdir -p "/home/$name/.cache/zsh/"

# dbus UUID must be generated for Artix runit.
dbus-uuidgen >/var/lib/dbus/machine-id

# Use system notifications for Brave on Artix
echo "export \$(dbus-launch)" >/etc/profile.d/dbus.sh

# Enable backlight control
{ [ "$(ls /sys/class/backlight/)" = "intel_backlight" ] && [ ! -f /etc/X11/xorg.conf.d/20-intel.conf ]; } && printf 'Section "Device"
    Identifier  "Intel Graphics"
    Driver      "intel"
    Option      "Backlight"  "intel_backlight"
EndSection' >/etc/X11/xorg.conf.d/20-intel.conf

# Enable tap to click
[ ! -f /etc/X11/xorg.conf.d/40-libinput.conf ] && printf 'Section "InputClass"
    Identifier "libinput touchpad catchall"
    MatchIsTouchpad "on"
    MatchDevicePath "/dev/input/event*"
    Driver "libinput"
    # Enable left mouse button by tapping
    Option "Tapping" "on"
EndSection' >/etc/X11/xorg.conf.d/40-libinput.conf

[ ! -f /usr/share/libalpm/hooks/statusbar.hook ] && printf '[Trigger]
Operation = Upgrade
Type = Package
Target = *

[Action]
Description = Updating statusbar...
When = PostTransaction
Exec = /usr/bin/pkill -RTMIN+16 dwmblocks' >/usr/share/libalpm/hooks/statusbar.hook

# Set up pam-gnupg
pamgnupg || error "User exited."

# Set up ecryptfs
ecryptfssetup || error "User exited."

# Set up ufw
ufwsetup || error "User exited."

# Set up samba
sambasetup || error "User exited."

# Set up bluez
bluezsetup || error "User exited."

# Set up cronjob
cronsetup || error "User exited."

# Set up ssh
sshsetup || error "User exited."

# Set up vpn
vpnsetup || error "User exited."

# Set up clamshell mode
#elogindsetup || error "User exited."

# Set up gpu
microsetup || error "User exited."

# Set up tlp
tlpsetup || error "User exited."

# Set up bbswitch
bbswitchsetup || error "User exited."

# Get Librewolf installed with add-ons and non-bad settings.
librewolfsetup || error "User exited."

# Clone TheSiahxyz's repositories
[ "$putrepo" = "y" ] && {
  putgitrepo "$passwordrepo" "/home/$name/.local/share" "$repobranch"
  putgitrepo "$neetcoderepo" "/home/$name/Private/git" "$repobranch"
  putgitrepo "$obsidianrepo" "/home/$name/Private/git" "$repobranch"
  putgitrepo "$webrepo" "/home/$name/Private/git" "$repobranch"
}

# Make grub fast
[ -z "$(xrandr | grep '1024x768')" ] || sed -Ei "s/^(GRUB_GFXMODE=).*/\11024x768x8/" /etc/default/grub
grub-mkconfig -o /boot/grub/grub.cfg >/dev/null 2>&1

# Allow wheel users to sudo with password and allow several system commands
# (like `shutdown` to run without password).
addsudo || error "Failed to add $name sudoers."

# Set up dash
dashsetup || error "Failed to set up dash"

# Last message! Install complete!
finalize