host info updates
[distro-setup] / switch-mail-host
index 12bf126e1f2512179915933ebacf0ebeb6ec0513..053134aac9ace8b5981e551c2653851899c6c29e 100644 (file)
@@ -1,17 +1,44 @@
 #!/bin/bash
+# I, Ian Kelling, follow the GNU license recommendations at
+# https://www.gnu.org/licenses/license-recommendations.en.html. They
+# recommend that small programs, < 300 lines, be licensed under the
+# Apache License 2.0. This file contains or is part of one or more small
+# programs. If a small program grows beyond 300 lines, I plan to switch
+# its license to GPL.
 
-source /usr/local/lib/err
+# Copyright 2024 Ian Kelling
+
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+
+#     http://www.apache.org/licenses/LICENSE-2.0
+
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+set -e; . /usr/local/lib/bash-bear; set +e
 
 usage() {
   cat <<EOF
-Usage: ${0##*/} [OPTIONS] push|pull HOST
+Usage: switch-mail-host|switch-host2 [OPTIONS] push|pull HOST
 
 Turn off mail receiving on OLD_HOST, run btrbk to move mail to NEW_HOST,
 turn on mail receiving on NEW_HOST.  Assumes we want to move all
 filesystems unless passing -o.
 
+-a         Avoid snapshot /a, /q, and similar. If we haven't
+           made any changes in the last hour, there is no
+           need to snapshot anything but /o, and we will
+           just do that once.
 -i         Disallow incremental backup.
 -o         Only btrbk /o, instead of all filesystems.
+--force    Run even though our local state does not say that MAIL_HOST is
+           us when pushing or HOST when pulling.
 -h|--help  Print help and exit.
 
 I used to adjust home network dns so NEW_HOST resolves locally if it is
@@ -20,9 +47,11 @@ on the internet. Email can wait.
 
 Note: Uses GNU getopt options parsing style
 EOF
-  exit $1
+  exit 0
 }
 
+script_name="${BASH_SOURCE[0]}"
+script_name="${script_name##*/}"
 
 restore_new_btrbk=false
 restore_old_btrbk=false
@@ -37,10 +66,11 @@ err-cleanup() {
   fi
 }
 
-pre="${0##*/}:"
+pre="$script_name:"
 m() { printf "$pre %s\n"  "$*"; "$@"; }
 e() { printf "$pre %s\n"  "$*"; }
 err() { echo "$pre ERROR: $*" >&2; }
+die() { printf "%s\n" "$*" >&2; echo "exiting with status 1" >&2; exit 1; }
 
 if [[ $EUID != 0 ]]; then
   err "requires running as root"
@@ -50,15 +80,33 @@ fi
 
 ##### begin command line parsing ########
 
+mail_only=false
+host2_only=false
 force=false
-mp_args="-m /o,/q,/a"
-temp=$(getopt -l force,help ioh "$@") || usage 1
+force_arg=
+pull_reexec=false
+mp_args="-m /o,/a,/q,/qd,/qr"
+check_installed=false
+orig_args=("$@")
+if ! temp=$(getopt -l check-installed,force,pull-reexec,help afioh "$@"); then
+  err "args invalid. args=$*"
+fi
 eval set -- "$temp"
 while true; do
   case $1 in
-    --force) force=true ;;
+    -a) snapshot_arg=resume ;;
+    --force|-f)
+      force=true
+      force_arg=-f
+      ;;
+    --check-installed)
+      check_installed=true
+      ;;
     -i) incremental_arg="-i" ;;
-    -o) mp_args="-m /o" ;;
+    # internal option for rerunning under newer old_host when doing pull
+    --pull-reexec) pull_reexec=true;;
+    -o)
+      mail_only=true ;;
     -h|--help) usage ;;
     --) shift; break ;;
     *) echo "$0: Internal error! unexpected args: $*" ; exit 1 ;;
@@ -67,35 +115,122 @@ while true; do
 done
 
 
-(( $# == 2 )) || usage 1
+if (( $# != 2 )) && ! $check_installed; then
+  err expected 2 args, got $#
+fi
 
 if [[ ! $HOSTNAME ]]; then
   err "\$HOSTNAME is unset"
   exit 1
 fi
 
-case $1 in
+uninstalled-file-die() {
+  die "on host=$HOSTNAME, uninstalled file $1. run install-my-scripts or rerun with -f"
+}
+
+
+source /a/bin/bash_unpublished/source-state
+
+direction=$1
+host=$2
+
+case $script_name in
+  switch-mail-host)
+    if [[ $MAIL_HOST != "$HOST2" ]]; then
+      mail_only=true
+    fi
+    ;;
+  switch-host2)
+    host2_only=true
+    ;;
+  *)
+    err unexpected script name
+    ;;
+esac
+
+if $mail_only; then
+  mp_args="-m /o"
+elif $host2_only; then
+  mp_args="-m /a,/q,/qd,/qr"
+fi
+
+
+if ! $force && { $check_installed || [[ $direction == push ]]; } ; then
+  install_bin_files=(
+    mount-latest-subvol
+    check-subvol-stale
+    btrbk-run
+    switch-mail-host
+  )
+  for f in ${install_bin_files[@]}; do
+    if ! diff -q /a/bin/ds/$f /usr/local/bin/$f; then
+      uninstalled-file-die $f
+    fi
+  done
+  if ! diff -q /a/bin/bash-bear-trap/bash-bear /usr/local/lib/bash-bear; then
+    uninstalled-file-die err
+  fi
+  if $check_installed; then
+    exit 0
+  fi
+fi
+
+
+case $direction in
   push)
     old_host=$HOSTNAME
     old_hostname=$HOSTNAME
-    new_host=$2
+    new_host=$host
     bbk_args="-t $new_host"
     new_shell="ssh -F $HOME/.ssh/confighome root@$new_host"
-    $new_shell -v hostname
-    new_hostname=$($new_shell hostname)
+    if ! new_hostname=$($new_shell hostname); then
+      echo "$pre: error: failed ssh. retrying failed $new_shell with -v for more info:"
+      $new_shell -v hostname
+    fi
     ;;
   pull)
-    old_host=$2
+    old_host=$host
     new_host=$HOSTNAME
     new_hostname=$HOSTNAME
     bbk_args="-s $old_host"
     old_shell="ssh -F $HOME/.ssh/confighome root@$old_host"
-    # tests ssh connection
-    if ! old_hostname=$($old_shell hostname); then
-      echo "retrying failed $old_shell with -v"
+    # tests ssh connection. crafted this to not need to do escape chars
+
+    if ! $mail_only && ! $pull_reexec ; then
+      if ! $force; then
+        if ! $old_shell switch-mail-host --check-installed; then
+          die "failed: $old_shell switch-mail-host --check-installed"
+        fi
+      fi
+      tmpd=$(mktemp -d)
+      files=(
+        /usr/local/{bin/{unsaved-buffers{,.el},switch-mail-host},lib/bash-bear}
+      )
+      m scp -F $HOME/.ssh/confighome \
+        ${files[@]/#/root@$old_host:} $tmpd
+      diff=false
+      for f in ${files[@]}; do
+        if ! diff -q $tmpd/${f##*/} $f; then
+          m install -T $tmpd/${f##*/} $f
+          diff=true
+        fi
+      done
+      if $diff; then
+        e "found different version on old_host=$old_host, reexecing"
+        m /usr/local/bin/switch-mail-host --pull-reexec "${orig_args[@]}"
+        exit 0
+      fi
+      rm -r -- $tmpd
+    fi
+
+    f=/a/bin/bash_unpublished/source-state
+    if ! old_info=$($old_shell "hostname; sed -n s,.*MAIL_HOST=,,p $f; sed -n s,.*HOST2=,,p $f"); then
+      echo "$pre: error: failed ssh. retrying failed $old_shell with -v for more info:"
       $old_shell -v hostname
       exit 1
     fi
+    read -d '' -r old_hostname MAIL_HOST HOST2 <<<"$old_info" || (( $? == 1 ))
+
     ;;
   *)
     err invalid first argument
@@ -103,11 +238,17 @@ case $1 in
     ;;
 esac
 
-source /a/bin/bash_unpublished/source-state
 
-if [[ $old_hostname != "$MAIL_HOST" ]] && ! $force; then
-  err "\$old_hostname($old_hostname) != \$MAIL_HOST($MAIL_HOST). Rerun with --force if you really want this."
-  exit 1
+if ! $force; then
+  if $host2_only; then
+    if [[ $old_hostname != "$HOST2" ]]; then
+      err "\$old_hostname($old_hostname) != \$HOST2($HOST2). Rerun with --force if you really want this."
+      exit 1
+    fi
+  elif [[ $old_hostname != "$MAIL_HOST" ]]; then
+    err "\$old_hostname($old_hostname) != \$MAIL_HOST($MAIL_HOST). Rerun with --force if you really want this."
+    exit 1
+  fi
 fi
 
 if [[ ! $new_host || ! $old_host ]]; then
@@ -148,35 +289,36 @@ while $active; do
   done
 done
 
-# ensure these are unused before doing anything
-
-e "On $new_host: umounting /m and /o, checking emacs"
-$new_shell bash -s <<'EOF'
-set -eE
-if pgrep -f 'emacs --daemon' &>/dev/null; then
-  bufs="$(emacsclient --eval "$(cat /a/bin/ds/unsaved-buffers.el)"| sed '/^"nil"$/d;s/^"(/E: /;s/)"$//')"
-  if [[ $bufs ]]; then
-    echo "error: on $HOSTNAME, unsaved emacs files: $bufs" >&2
-    exit 1
-  fi
-fi
+if ! $host2_only; then
+  # ensure these are unused before doing anything
+  e "On $new_host: umounting /m and /o, checking emacs"
+  {
+    cat /usr/local/bin/unsaved-buffers
+    if ! $host2_only; then
+      cat <<EOF
 for dir in m o; do
-  if mountpoint -q /$dir; then
-    echo On $new_host: umount /$dir
-    umount /$dir
+  if mountpoint -q /\$dir; then
+    echo On $new_host: umount /\$dir
+    umount /\$dir
   fi
 done
 EOF
+    fi
+  } | $new_shell bash -s
+fi
 
-$old_shell bash -s <<'EOF'
-if pgrep -f 'emacs --daemon' &>/dev/null; then
-  bufs="$(emacsclient --eval "$(cat /a/bin/ds/unsaved-buffers.el)"| sed '/^"nil"$/d;s/^"(/E: /;s/)"$//')"
-  if [[ $bufs ]]; then
-    echo "error: on $HOSTNAME, unsaved emacs files: $bufs" >&2
-    exit 1
-  fi
+if ! $mail_only; then
+  cat /usr/local/bin/unsaved-buffers - <<'EOF' |  $old_shell bash -s
+
+# Try to prevent emacs from saving stale data it has in memory to disk. eg: files, recentf list, etc.
+# But if emacs ignores the signal, let it live.
+pkill -xf 'emacs( --daemon| -f znc-all)' ||:
+
+if [[ -e /p/profanity-here ]]; then
+  systemctl disable --now profanity
 fi
 EOF
+fi
 
 # previously, I was checking to see if the new mail host
 # is on my home network, then changing my home dns
@@ -194,31 +336,51 @@ EOF
 
 
 e Running initial btrbk
-if ! m btrbk-run -v $bbk_args $incremental_arg $mp_args; then
-  ret=$?
+m btrbk-run -v $bbk_args $force_arg $incremental_arg $mp_args $snapshot_arg || ret=$?
+if (( ret )); then
   err "failed initial btrbk"
   exit $ret
 fi
 
-if ! m $old_shell /a/exe/primary-setup $new_hostname; then
-  ret=$?
-  err "failed \$old_shell primary-setup \$new_hostname. fix and rerun switch-mail-host"
+if ! $mail_only; then
+  m $old_shell sed -ri "s/HOST2=.*/HOST2=$new_hostname/" /a/bin/bash_unpublished/source-state
+  m $new_shell sed -ri "s/HOST2=.*/HOST2=$new_hostname/" /a/bin/bash_unpublished/source-state
+fi
+
+if $host2_only; then
+  if [[ $old_hostname != "$MAIL_HOST" && $old_hostname != kd ]]; then
+    m $old_shell systemctl --now disable btrbk.timer
+  fi
+  m $new_shell systemctl --now enable btrbk.timer
+  if [[ -e /p/profanity-here ]]; then
+    m $new_shell systemctl --now enable profanity
+  fi
+  exit 0
+fi
+
+m $old_shell /a/exe/primary-setup $new_hostname || ret=$?
+if (( ret )); then
+  err "failed \$old_shell primary-setup \$new_hostname. fix and rerun $script_name"
   exit $ret
 fi
 
-# Try to prevent emacs from saving stale data it has in memory to disk. eg: files, recentf list, etc.
-# But if emacs ignores the signal, let it live.
-m $new_shell killall -q emacs ||:
 
 e Running main btrbk
-m btrbk-run -v $bbk_args $incremental_arg -m /o || ret=$?
+m btrbk-run -v --fast $bbk_args $force_arg $incremental_arg -m /o || ret=$?
 if (( ret )); then
-  bang="$(printf "$(tput setaf 5)█$(tput sgr0)%.0s" 1 2 3 4 5 6 7)"
+  bang="███████"
   e $bang failed btrbk of /o. restoring old host as primary
-  m $old_shell /a/exe/primary-setup localhost
+  if ! m $old_shell /a/exe/primary-setup localhost; then
+    die "due to failed btrbk of /o, we tried to restore old host as primary, but then we failed at that too. To resolve: Fix & rerun switch-mail-host, or fix and rerun primary-setup localhost on old shell so you have a working mail server and then rerun switch-mail-host."
+  fi
+  e finished restoring old host as primary, now exiting $ret due to earlier failed btrbk of /o.
   exit $ret
 fi
 
+# new system is usable at this point
+blocks=██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████
+printf "%s\n" "${blocks:0:${COLUMNS:-100}}"
+
 # once I accidentally accepted incoming mail on old host. I used this script to copy over that mail:
 #
 # die=false; for d in o.leaf.2021-05-29T10:02:08-0400/m/{4e,md,4e2}/{,l/}!(*myarchive)/new; do if $die; then break; fi; find $d -type f -mtime -5 | while read -r f; do dir="${f%new/*}"; dir="btrbk/o.20210530T000011-0400/${dir#*/}"; fname="${f##*/}"; [[ -e $dir/new/$fname || -e $dir/cur/$fname ]] && continue; if ! e cp -a $f /${dir#*/*/}new; then echo failed cp; die=true; break; fi ; done; done
@@ -227,8 +389,8 @@ fi
 #
 # shopt -s nullglob; find . -type f -mtime -2 | while read -r f; do a=( /m/4e/Sent/cur/${f%,*}* ); if (( ${#a[@]} )); then e exists $a; else m cp -a $f /m/4e/Sent/cur; fi; done
 
-if ! m $new_shell /a/exe/primary-setup localhost; then
-  ret=$?
+m $new_shell /a/exe/primary-setup localhost || ret=$?
+if (( ret )); then
   err "failed final primary-setup, just fix and rerun: $new_shell /a/exe/primary-setup localhost"
   exit $ret
 fi