shellcheck, better automated upgrades
[distro-setup] / distro-begin
1 #!/bin/bash -l
2 # Copyright (C) 2016 Ian Kelling
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # for setting up a new machine
17 # usage: $0 [-r] HOSTNAME
18
19 # tips:
20 # run any sudo command first so your pass is cached
21 # set the scrollback to unlimited in case something goes wrong
22
23
24 ####### begin setup environment #######
25
26
27 ### make ssh interactive shell run better. for when running line interactively line by line
28 sudo bash -c 'source /a/c/.bashrc && source /a/exe/ssh-emacs-setup'
29
30
31 ##### setup error handling
32 interactive=true # set this to false to force set -x
33 [[ $- == *i* ]] || interactive=false
34 if ! $interactive; then
35 set -x
36 fi
37 source /a/bin/errhandle/err
38
39 ### setup logging
40 exec &> >(sudo tee -a /var/log/distro-begin)
41 echo "$0: $(date): starting now)"
42
43
44 ### sanity checking
45 if [[ $EUID == 0 ]]; then
46 if getent passwd iank || getent passwd ian ; then
47 echo "$0: error: running as root. unprivileged user exists. use it."
48 exit 1
49 else
50 echo "$0: warning: running as root. I will setup users then exit"
51 fi
52 fi
53
54
55 ### arg parsing
56 recompile=false
57 while [[ $1 == -* ]]; do
58 case $1 in
59 -r) recompile=true; shift ;;
60 esac
61 done
62 if [[ $1 ]]; then
63 export HOSTNAME=$1
64 fi
65
66
67 ##### variables/env setup
68 script_dir="$(readlink -f "${BASH_SOURCE[@]}")"; script_dir=${script_dir%/*}
69 # shellcheck source=./pkgs
70 source $script_dir/pkgs
71 set +x
72 source /a/bin/distro-functions/src/identify-distros
73 $interactive || set -x
74 for f in iank-dev htpc kd x2 x3 frodo tp li lj demohost kw fz; do
75 eval "$f() { [[ $HOSTNAME == $f ]]; }"
76 done
77 codename=$(debian-codename)
78 has_wayland() { [[ $codename == buster ]]; }
79 has_x() { [[ $codename != buster ]]; }
80 has_monitor() { ! linode ; }
81 linode() { lj || li; }
82 has_btrfs() { ! linode; }
83 home_network() { ! linode; }
84 encrypted() { has_p; }
85 shopt -s extglob
86 export GLOBIGNORE=*/.:*/..
87 umask 022
88 PATH="/a/exe:$PATH"
89 sed="sed --follow-symlinks"
90
91 ####### end setup environment #######
92
93
94
95
96 ##### begin setup encryption scripts ######
97 if encrypted; then
98 # I tried making a service which was dependent on reboot.target,
99 # but it happened too late in the shutdown process.
100 sudo dd of=/etc/systemd/system/keyscripton.service <<'EOF'
101 [Unit]
102 Description=Turn on automatic decryption of drives on boot
103 # tried using graphical.target, but it made my display manager restart before rebooting.
104 # generally, I don't think targets order shutdown like they do startup.
105 # So, I did systemd-analyze plot > something.svg, and picked a reliably started
106 # service that happens late in the game.
107 After=ntp.service
108 DefaultDependencies=no
109 # not sure if needed, makes sure we shut down before reboot.target
110 Conflicts=reboot.target
111
112 [Service]
113 Type=oneshot
114 RemainAfterExit=yes
115 ExecStart=/bin/true
116 ExecStop=/a/exe/keyscript-on
117
118 [Install]
119 WantedBy=keyscriptoff.service
120 EOF
121 sudo systemctl daemon-reload # needed if the file was already there
122 sudo systemctl stop keyscripton.service
123 # sudo systemctl start keyscripton.service
124 sudo systemctl enable keyscripton.service
125
126 sudo dd of=/etc/systemd/system/keyscriptoff.service <<'EOF'
127 [Unit]
128 Description=Turn off automatic decryption of drives on boot
129
130 [Service]
131 Type=oneshot
132 ExecStart=/a/exe/keyscript-off
133
134 [Install]
135 WantedBy=multi-user.target
136 EOF
137 sudo systemctl daemon-reload # needed if the file was already there
138 sudo systemctl enable keyscriptoff.service
139 sudo systemctl start keyscriptoff.service
140
141 # from /usr/share/doc/dropbear-initramfs/README.initramfs.gz
142 while read -r m _; do /sbin/modinfo -F filename "$m"; done </proc/modules | \
143 sed -nr "s@^/lib/modules/`uname -r`/kernel/drivers/net(/.*)?/([^/]+)\.ko\$@\2@p" \
144 | sudo dd of=/etc/initramfs-tools/modules
145 sudo apt-get -y install initramfs-tools-core
146 # initram auth keys get setup with rootsshsync
147 # then for remote unlock, ssh and do this once per crypt disk:
148 # echo -n PASS >/lib/cryptsetup/passfifo
149 fi
150 ##### end setup encryption scripts ######
151
152
153 # disabled until its fixed up
154 # install-myqueue
155
156 # todo, it would be nice to cut down on some of the output
157
158 ##### fedora prereq/fundamental settings
159 if isfedora; then
160 # comment out line disallowing calling sudo in scripts
161 sudo $sed -i 's/^Defaults *requiretty/#\0 # ian commented/' /etc/sudoers
162 # turn on magic sysrq commands
163 echo 1 > sudo dd of=/proc/sys/kernel/sysrq
164 echo "kernel.sysrq = 1" > /etc/sysctl.d/90-sysrq.conf
165 # selinux is not user friendly. Like, you enable samba, but you haven't run the magic selinux commands so it doesn't work
166 # and you have no idea why.
167 sudo $sed -i 's/^\(SELINUX=\).*/\1disabled/' /etc/selinux/config
168 selinuxenabled && sudo setenforce 0
169 fi
170
171
172 #### rerun my fai-time scripts
173 # already ran for pxe installs, but used for vps & updates
174 distro=$(distro-name)
175 case $distro in
176 ubuntu|debian|trisquel)
177 sudo bash -c ". /a/bin/fai/fai-wrapper && /a/bin/fai/fai/config/scripts/GRUB_PC/11-iank"
178 ;;
179 *)
180 sudo bash -c ". /a/bin/fai/fai-wrapper &&
181 /a/bin/fai/fai/config/distro-install-common/end"
182 ;;
183 esac
184
185 ###### setup hostname
186 sudo $sed -i '/^127\.0\.1\.1/d' /etc/hosts
187 echo "127.0.1.1 $HOSTNAME.b8.nz $HOSTNAME" | sudo tee -a /etc/hosts
188
189
190 ##### exit first stage if running as root
191 if [[ $EUID == 0 ]]; then
192 echo "$0: running as root. exiting now that users are setup"
193 exit 0
194 fi
195
196
197 #### setup bash for root
198 for x in /a/c/{.bashrc,brc,.bash_profile,.profile,.inputrc,path_add_function}; do
199 sudo -i <<EOF
200 PATH="/a/exe:$PATH"
201 lnf $x /root
202 EOF
203 done
204
205 ###### do conflink
206 # li needs the bind group before conflink
207 if [[ $HOSTNAME == li ]]; then
208 getent group bind &>/dev/null || sudo groupadd -r bind
209 fi
210 # this needs to be before installing pacserve so we have gpg conf.
211 conflink
212
213 ###### bash environment setup
214 set +x
215 err-allow
216 source /etc/profile.d/environment.sh
217 source ~/.bashrc
218 err-catch
219 $interactive || set -x
220
221
222 #### setup passwordless sudo
223 tu /etc/sudoers <<EOF
224 $USER ALL=(ALL) NOPASSWD: ALL
225 Defaults env_keep += SUDOD
226 # makes ubuntu be like debian
227 # https://unix.stackexchange.com/a/91572
228 Defaults always_set_home
229 # default setting is to have minimum umask of 0022
230 # This lets us have user-specific umasks which are more permissive.
231 # I did this for transmission and set it's umask gecos on install,
232 # see there for more info.
233 Defaults !umask
234 EOF
235
236
237 #### setup firefox backport
238 ## ian: disabled. backports are not being published atm due to rust packaging issue
239 # if isdeb; then
240 # codename=$(debian-codename)
241 # if isdebian-stable && has_x; then
242 # s dd of=/etc/apt/sources.list.d/mozilla-iceweasel.list <<EOF
243 # deb http://mozilla.debian.net/ $codename-backports firefox-release
244 # deb-src http://mozilla.debian.net/ $codename-backports firefox-release
245 # EOF
246 # p update
247 # # take care of mozilla signing errors in previous command
248 # pi pkg-mozilla-archive-keyring
249 # fi
250 # p update
251 # fi
252
253
254 ###### arch aur wrapper setup
255 if isarch; then
256 #https://wiki.archlinux.org/index.php/Arch_User_Repository#Installing_packages
257 sudo pacman -S --noconfirm --needed base-devel jq
258 # pacaur seems to be the best, although it + cower has a few minor bugs,
259 # its design goals seem good, so, going for it.
260
261 aurpi() {
262 for p in "$@"; do
263 tempdir=$(mktemp -d)
264 pushd $tempdir
265 aurex "$p"
266 makepkg -sri --skippgpcheck --noconfirm
267 popd
268 rm -rf $tempdir
269 done
270 }
271 aurpi cower pacaur
272
273 pi pacserve
274
275 x=$(mktemp); /usr/bin/pacman.conf-insert_pacserve >$x
276 sudo dd of=/etc/pacman.conf if=$x; rm $x
277 sudo systemctl enable pacserve.service
278 sudo systemctl start pacserve.service
279
280 fi
281
282 #### update all packages
283 pup
284
285
286 ###### p1 packages install ######
287 if isarch; then
288 # requirement for trash-cli.
289 # background: strange error if just installing trash-cli: "pyalpm requires python",
290 # so I see that it requires python2, and installing that manually fixes it.
291 # I didn\'t see this on earlier installation, main thing which changed was
292 # pacserve, so not sure if it\'s related.
293 pi python2
294 fi
295 pi ${p1[@]}
296
297
298 ######## fix evbug bug ######
299 case $distro in
300 trisquel|ubuntu)
301 # noticed in flidas.
302 #https://bugs.launchpad.net/ubuntu/+source/module-init-tools/+bug/240553
303 #https://wiki.debian.org/KernelModuleBlacklisting
304 #common advice when searching is to use /etc/modprobe.d/blacklist.conf,
305 #but that file won't work and will get automatically reverted
306 sudo rmmod evbug ||: # might not be loaded yet
307 file=/etc/modprobe.d/evbug.conf
308 line="blacklist evbug"
309 if ! grep -xFq "$line" $file; then
310 sudo dd of=$file 2>/dev/null <<<"$line"
311 sudo depmod -a
312 sudo update-initramfs -u
313 fi
314 ;;
315 esac
316
317
318 ###### link files
319 # convenient to just do all file linking in one place
320 s lnf -T /a/bin /b
321 s lnf -T /nocow/t /t
322 if has_p; then
323 lnf -T /p/News ~/News
324 fi
325 s lnf /q/root/.editor-backups /q/root/.undo-tree-history \
326 /a/opt /a/c/.emacs.d $HOME/mw_vars /k/backup /root
327 pi rsync # needed for rootsshsync
328 /a/bin/ds/install-my-scripts # needed for rootsshsync
329 rootsshsync
330 s lnf /a/c/.vim /a/c/.vimrc /a/c/.gvimrc /root
331 if has_p; then
332 # for dovecot
333 lnf -T /i/k/mboxes ~/mail
334 fi
335
336
337
338 ##### install xinput
339 if has_x; then
340 case $(distro-name) in
341 trisquel|ubuntu|debian)
342 pi xinput
343 ;;
344 fedora)
345 pi xinput_calibrator
346 ;;
347 arch)
348 pi xorg-xinput
349 ;;
350 esac
351
352 #### install redshift
353 case $(distro-name) in
354 trisquel|ubuntu|debian)
355 # recommends gets us geoclue (for darkening automatically at night i assume),
356 # which recommends modemmanager, which is annoying to fix for the model01 keyboard.
357 pi --no-install-recommends gtk-redshift
358 ;;&
359 fedora)
360 pi redshift-gtk
361 ;;&
362 arch)
363 pi redshift
364 ;;&
365 esac
366 fi
367
368 if has_wayland; then
369 pi sway xwayland
370 # originally used xkbcomp, documented in input-setup.sh, this doesnt
371 # work under wayland, but its still useful for creating the config,
372 # then modifying the system files.
373 s sed -i.orig '/key *<KPMU> *{/,/}/s/KP_Multiply/underscore/g' /usr/share/X11/xkb/symbols/keypad
374 fi
375
376
377
378 #### arch specific early packages
379 case $(distro-name) in
380 arch)
381 # pkgfile is like apt-cache
382 pi pkgfile
383 s pkgfile --update
384 ;;
385 esac
386
387 #### fedora specific packages
388 case $(distro-name) in
389 fedora)
390 # todo, this could probably come later
391 p -y groupinstall development-tools c-development books admin-tools
392 pi man-pages
393 ;;
394 # other distros unknown
395 esac
396
397 #### enable trim
398 # enable trim for volume delete, other rare commands
399 sudo $sed -ri 's/( *issue_discards\b).*/\1 = 1/' /etc/lvm/lvm.conf
400 if encrypted; then
401 # flidas or so, these units arent built-in
402 if isdeb && ! systemctl list-unit-files | grep -xF fstrim.timer &>/dev/null ; then
403 sudo cp /usr/share/doc/util-linux/examples/fstrim.{service,timer} /etc/systemd/system
404 fi
405 # does weekly trim
406 sudo systemctl enable fstrim.timer
407 fi
408
409 ##### make extra dirs
410 dirs=(/mnt/{1,2,3,4,5,6,7,8,9} /nocow/t)
411 s mkdir -p "${dirs[@]}"
412 s chown $USER:$USER "${dirs[@]}"
413
414 ###### setup /i
415 tu /etc/fstab <<'EOF'
416 /i/w /w none bind,noauto 0 0
417 /i/k /k none bind,noauto 0 0
418 EOF
419 if ! mountpoint /kr; then
420 s mkdir -p /kr
421 s chown $USER:user2 /kr
422 fi
423 if home_network; then
424 if [[ $HOSTNAME == frodo ]]; then
425 tu /etc/fstab <<'EOF'
426 /k /kr none bind,noauto 0 0
427 EOF
428 else
429 tu /etc/fstab <<'EOF'
430 frodo:/k /kr nfs noauto 0 0
431 EOF
432 fi
433 fi
434 s mkdir -p /q /i/{w,k}
435 for dir in /{i,w,k}; do
436 if mountpoint $dir; then continue; fi # already mounted
437 s mkdir -p $dir
438 s chown $USER:$USER $dir
439 done
440 # not needed for all hosts, but rather just keep it uniform
441 s mkdir -p /mnt/iroot
442 # debian auto mounting of multi-disk encrypted btrfs is busted. It is
443 # in jessie, and in stretch as of 11/26/2016 I have 4 disks in cryptab,
444 # based on 3 of those, it creates .device units for /dev/mapper/dev...
445 # then waits endlessly for them on bootup, after the /dev/mapper disks
446 # have already been created and exist. todo: create a simple repro
447 # for this in a vm and report it upstream.
448 if has_btrfs || home_network; then
449 pi nfs-common
450 s dd of=/root/imount <<'EOF'
451 #!/bin/bash
452 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
453 set -eE -o pipefail
454 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
455 for dir in /i /mnt/iroot /k /kr /w; do
456 if ! mountpoint $dir &>/dev/null && \
457 awk '{print $2}' /etc/fstab | grep -xF $dir &>/dev/null; then
458 if awk '{print $3}' /etc/fstab | grep -xF nfs &>/dev/null; then
459 mount $dir || echo "warning: failed to mount nfs on $dir"
460 else
461 mount $dir
462 fi
463 fi
464 done
465 EOF
466 s chmod +x /root/imount
467
468 s dd of=/etc/systemd/system/imount.service <<EOF
469 [Unit]
470 Description=Mount /i and related mountpoints
471 Before=syncthing@$USER.service
472
473 [Service]
474 Type=oneshot
475 ExecStart=/root/imount
476
477 [Install]
478 RequiredBy=syncthing@$USER.service
479 # note /kr needs networking, this target is the simplest way to
480 # time it when the network should be up, but not do something
481 # dumb like delay startup until the network is up. It happens
482 # at some time after network.target
483 WantedBy=multi-user.target
484 EOF
485 sudo systemctl daemon-reload # needed if the file was already there
486 sudo systemctl enable imount.service
487 sudo systemctl start imount.service
488 fi
489
490 ##### setup /nocow.
491 # a nocow dir that is common to multiple distros installed on the same system
492 dir=/nocow
493 if has_btrfs; then
494 if ! mountpoint $dir; then
495 subvol=/mnt/root/nocow
496 if [[ ! -e $subvol ]]; then
497 s btrfs subvolume create $subvol
498 s chown root:1000 $subvol
499 s chattr +C $subvol
500 fi
501
502 first_root_crypt=$(awk '$2 == "/" {print $1}' /etc/mtab)
503 tu /etc/fstab <<EOF
504 $first_root_crypt /nocow btrfs noatime,subvol=nocow 0 0
505 EOF
506 s mkdir -p $dir
507 s chown $USER:$USER $dir
508 s mount $dir
509 fi
510 else
511 sudo mkdir -p $dir
512 fi
513
514
515 ##### setup email
516 mail-setup
517
518 #### ubuntu nicety
519 if isubuntu; then
520 # disable crash report annoying dialogs.
521 s dd of=/etc/default/apport <<<'enabled=0'
522 fi
523
524
525 ##### install emacs
526 if isarch; then
527 # emacs git build was broken last time i checked,
528 x=$(mktemp -d)
529 pushd $x
530 aurex emacs-git
531 makepkg -si --noconfirm
532 popd
533 rm -rf $x
534 pi hunspell hunspell-en
535 else
536 if $recompile; then
537 /a/bin/buildscripts/emacs
538 else
539 /a/bin/buildscripts/emacs --no-r || /a/bin/buildscripts/emacs
540 fi
541 fi
542
543 ##### install laptop hardware packages
544 if tp || x2 || x3; then
545 case $distro in
546 debian)
547 pi task-laptop
548 ;;
549 ubuntu|trisquel)
550 # the exact packages that task-laptop would install, since ubuntu
551 # doesn\'t have this virtual in practice package.
552 pi avahi-autoipd bluetooth powertop iw wireless-tools wpasupplicant
553 ;;
554 # todo: other distros unknown
555 esac
556 fi
557
558
559 ##### install x stuff
560 if has_monitor; then
561 pi ${p2[@]}
562 if has_x; then
563 pi i3
564 if isarch; then
565 # xorg-xmessage for displaying error messages.
566 # optional dependency in arch, standard elsewhere.
567 pi xorg-server xorg-xmessage xorg-xsetroot xorg-xinit
568 fi
569 fi
570 fi
571
572
573 ##### setup X autostart
574 if has_x; then
575 if isarch; then
576 # https://wiki.archlinux.org/index.php/Xinitrc
577 for homedir in /home/*; do
578 cp /etc/X11/xinit/xinitrc $homedir/.xinitrc
579 $sed -ri '/^ *twm\b/,$d' $homedir/.xinitrc
580 tee -a $homedir/.xinitrc <<'EOF'
581 /a/bin/desktop-20-autostart.sh
582 xsetroot -cursor_name left_ptr
583 exec xmonad
584 EOF
585 done
586 else
587 # todo, figure this out for arch if we ever try out gnome.
588 # install for multiple display managers in case we use one
589 if isdeb; then
590 dir=/etc/gdm3
591 elif isfedora; then
592 # fedora didn\'t have the 3.
593 dir=/etc/gdm
594 fi
595 s mkdir -p $dir/PostLogin
596 s command cp /a/bin/distro-setup/desktop-20-autostart.sh $dir/PostLogin/Default
597 s mkdir /etc/lightdm/lightdm.conf.d
598 s dd of=/etc/lightdm/lightdm.conf.d/12-iank.conf <<'EOF'
599 [SeatDefaults]
600 session-setup-script=/a/bin/distro-setup/desktop-20-autostart.sh
601 EOF
602 fi
603 fi
604
605
606 #### refix interactive ssh terminal
607 # the first pup command can kill off our /etc/ mod, so rerun this
608 /a/exe/ssh-emacs-setup
609
610
611 echo "$0: $(date): ending now"
612 exit 0