tune cronjobs
[distro-setup] / filesystem / usr / local / bin / myupgrade
1 #!/bin/bash
2 # Copyright (C) 2019 Ian Kelling
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4
5 # usage: set DEBUG env var to anything to output to stdout
6
7 # Note: running this inside a cronjob, it wont mail any output if we end
8 # up rebooting from this script.
9
10 if [ -z "$BASH_VERSION" ]; then echo "error: shell is not bash" >&2; exit 1; fi
11
12 source /usr/local/lib/err
13 pre="${0##*/}:"
14 PATH="/sbin:$PATH"
15 m() { printf "$pre %s\n" "$*"; "$@"; }
16 e() { printf "$pre %s\n" "$*"; }
17 err() { echo "[$(date +'%Y-%m-%d %H:%M:%S%z')]: $pre: $*" >&2; }
18
19 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
20
21 hn=$(hostname -f)
22 source /a/bin/bash_unpublished/source-state
23
24 d() {
25 if [[ $DEBUG ]]; then
26 pee cat "wall -n"
27 else
28 echo ok | sed 's/^/myupgrade /' | pee logger "wall -n"
29 fi
30 }
31 myreboot() {
32 for x in {30..1}; do
33 echo "pid $$. unattended upgrade, rebooting in $((x*10)) seconds" | wall -n
34 sleep 10
35 done
36 for x in {30..1}; do
37 if ! fuser /var/lib/dpkg/lock &> /dev/null; then
38 echo "pid $$. unattended upgrade, rebooting now" | d
39 /a/bin/ds/keyscript-on
40 /sbin/reboot
41 exit 0
42 fi
43 echo "pid $$. unattended upgrade reboot waiting 10 seconds for dpkg lock" | wall -n
44 sleep 10
45 done
46 echo "pid $$. dpkg locked for 5 minutes, automatic reboot failed" | d
47 }
48
49
50 # TODO: executed from cron, this doesnt sent an email when we reboot,
51 # because rebooting from the script stops the ability to send email.
52 # We should figure some workaround.
53
54 if ! out=$(/sbin/needrestart -p 2>&1); then
55 printf "%s\n\n" "$out"
56 if [[ $HOSTNAME != "$MAIL_HOST" ]]; then
57 myreboot
58 fi
59 fi