Files
emailwiz/lib/common.sh
T

182 lines
6.2 KiB
Bash

# emailwiz - common helpers (logging, staging, atomic install, backups)
# SPDX-License-Identifier: GPL-3.0-or-later
# shellcheck shell=sh
# Exit codes
EX_OK=0
EX_ERR=1
EX_USAGE=2
EX_VALIDATION=3
EX_UNSUPPORTED=4
EX_PENDING=10 # plan --detailed-exitcode: changes pending
EMAILWIZ_LOG=${EMAILWIZ_LOG:-/var/log/emailwiz.log}
EMAILWIZ_STATE=${EMAILWIZ_STATE:-/var/lib/emailwiz}
EMAILWIZ_BACKUPS=${EMAILWIZ_BACKUPS:-/var/backups/emailwiz}
if [ -t 2 ]; then
C_RED=$(printf '\033[31m'); C_YEL=$(printf '\033[33m')
C_GRN=$(printf '\033[32m'); C_BLU=$(printf '\033[34m'); C_OFF=$(printf '\033[0m')
else
C_RED=; C_YEL=; C_GRN=; C_BLU=; C_OFF=
fi
_logfile() {
# Only real (non-plan) runs as root write the persistent log.
[ "${MODE:-}" = apply ] || return 0
[ "$(id -u)" -eq 0 ] || return 0
printf '%s [%s] %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" "$2" >>"$EMAILWIZ_LOG" 2>/dev/null || :
}
log() { printf '%s==>%s %s\n' "$C_BLU" "$C_OFF" "$*" >&2; _logfile INFO "$*"; }
info() { printf ' %s\n' "$*" >&2; _logfile INFO "$*"; }
ok() { printf '%s ok%s %s\n' "$C_GRN" "$C_OFF" "$*" >&2; _logfile OK "$*"; }
warn() { printf '%swarn%s %s\n' "$C_YEL" "$C_OFF" "$*" >&2; _logfile WARN "$*"; }
err() { printf '%serror%s %s\n' "$C_RED" "$C_OFF" "$*" >&2; _logfile ERROR "$*"; }
die() { err "$1"; exit "${2:-$EX_ERR}"; }
have() { command -v "$1" >/dev/null 2>&1; }
need_root() {
[ "$(id -u)" -eq 0 ] || die "this command must run as root (try: sudo emailwiz $*)" "$EX_ERR"
}
# --- staging -----------------------------------------------------------------
# Desired state is rendered under $STAGE, mirroring the filesystem, e.g.
# $STAGE/etc/dovecot/dovecot.conf. $STAGE/.meta lists "path mode owner group
# reload-unit" for every staged file; $STAGE/.retire lists files to retire.
stage_init() {
STAGE=$(mktemp -d "${TMPDIR:-/tmp}/emailwiz-stage.XXXXXX")
: >"$STAGE/.meta"
: >"$STAGE/.retire"
: >"$STAGE/.notes"
: >"$STAGE/.actions"
trap 'rm -rf "$STAGE"' EXIT INT TERM
}
# stage_file PATH MODE OWNER GROUP UNIT (content on stdin)
stage_file() {
_p=$1
mkdir -p "$STAGE$(dirname "$_p")"
cat >"$STAGE$_p"
printf '%s %s %s %s %s\n' "$_p" "$2" "$3" "$4" "${5:--}" >>"$STAGE/.meta"
}
# stage_retire PATH UNIT REASON - move an obsolete file into the backup.
stage_retire() {
[ -e "$1" ] || return 0
printf '%s %s %s\n' "$1" "${2:--}" "$3" >>"$STAGE/.retire"
}
note() { printf '%s\n' "$*" >>"$STAGE/.notes"; }
# stage_action UNIT REASON - a service action needed even if no file changes.
stage_action() { printf '%s %s\n' "$1" "$2" >>"$STAGE/.actions"; }
# file_state PATH MODE OWNER GROUP -> prints "new", "changed", "meta" or "same"
file_state() {
if [ ! -e "$1" ]; then echo new; return; fi
if ! cmp -s "$STAGE$1" "$1"; then echo changed; return; fi
_cur=$(stat -c '%a %U %G' "$1")
[ "$_cur" = "$2 $3 $4" ] && echo same || echo meta
}
# install_atomic SRC DEST MODE OWNER GROUP - write via temp file + rename.
install_atomic() {
_dir=$(dirname "$2")
[ -d "$_dir" ] || install -d -m 0755 "$_dir"
_tmp=$(mktemp "$_dir/.emailwiz.XXXXXX")
cat "$1" >"$_tmp"
chown "$4:$5" "$_tmp"
chmod "$3" "$_tmp"
mv -f "$_tmp" "$2"
}
# --- backups -------------------------------------------------------------------
# Paths captured by every backup. Missing paths are skipped.
BACKUP_PATHS="/etc/postfix /etc/dovecot /etc/opendkim.conf /etc/default/opendkim
/etc/default/spamd /etc/fail2ban/jail.d /etc/systemd/system/opendkim.service.d
/etc/systemd/system/spamd.service.d /etc/systemd/system/emailwiz-certcheck.service
/etc/systemd/system/emailwiz-certcheck.timer /etc/systemd/system/emailwiz-backup.service
/etc/systemd/system/emailwiz-backup.timer /etc/aliases /etc/pam.d/dovecot
/etc/mailname /etc/emailwiz /var/lib/dovecot/sieve
/etc/letsencrypt/renewal-hooks/deploy/emailwiz-reload"
# backup_create LABEL [extra paths...] -> prints backup dir
backup_create() {
_label=$1; shift
_id="$(date +%Y%m%d-%H%M%S)-$_label"
_dir="$EMAILWIZ_BACKUPS/$_id"
install -d -m 0700 -o root -g root "$EMAILWIZ_BACKUPS"
install -d -m 0700 -o root -g root "$_dir"
_list=
for _p in $BACKUP_PATHS "$@"; do
[ -e "$_p" ] || continue
# Skip paths already covered by an earlier entry (e.g. DKIM_DIR in /etc/postfix).
_dup=no
for _q in $_list; do
case "${_p#/}/" in "$_q"/*) _dup=yes ;; esac
done
[ "$_dup" = yes ] || _list="$_list ${_p#/}"
done
# shellcheck disable=SC2086
tar -C / --numeric-owner -cpzf "$_dir/config.tar.gz" $_list
# shellcheck disable=SC2086
(cd / && find $_list -xdev \( -type f -o -type l \) -print) | sort >"$_dir/MANIFEST"
(cd "$_dir" && sha256sum config.tar.gz >SHA256SUMS)
: >"$_dir/created"
chmod 0600 "$_dir"/*
# A backup that cannot be read back is not a backup.
tar -tzf "$_dir/config.tar.gz" >/dev/null || die "backup verification failed: $_dir"
(cd "$_dir" && sha256sum -c --quiet SHA256SUMS) || die "backup checksum failed: $_dir"
printf '%s\n' "$_dir"
}
backup_prune() {
_keep=${1:-20}
[ -d "$EMAILWIZ_BACKUPS" ] || return 0
# Only prune automatic backups; manual/apply backups are kept.
find "$EMAILWIZ_BACKUPS" -mindepth 1 -maxdepth 1 -type d -name '*-scheduled' |
sort -r | tail -n +"$((_keep + 1))" | while read -r _d; do
rm -rf -- "$_d"
done
}
# shell-quote a value for single-quoted config output
squote() { printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"; }
# --- prompts -------------------------------------------------------------------
# NONINTERACTIVE=yes (setup --non-interactive): never prompt; values come from
# the environment/config, yes/no answers from the named variable (default no).
NONINTERACTIVE=${NONINTERACTIVE:-no}
# ask VAR QUESTION [DEFAULT] - current value of VAR wins over DEFAULT.
ask() {
eval "_cur=\${$1:-}"
_def=${_cur:-${3:-}}
if [ "$NONINTERACTIVE" = yes ]; then
eval "$1=\$_def"
return 0
fi
[ -t 0 ] || die "cannot prompt for '$2' without a terminal (use --non-interactive)" "$EX_USAGE"
printf '%s [%s]: ' "$2" "$_def" >&2
read -r _ans || _ans=
[ -n "$_ans" ] || _ans=$_def
eval "$1=\$_ans"
}
# confirm QUESTION [VAR] - 0 for yes. Non-interactive: value of VAR (yes/no).
confirm() {
if [ "$NONINTERACTIVE" = yes ]; then
[ -n "${2:-}" ] || return 1
_v=no
eval "_v=\${$2:-no}"
[ "$_v" = yes ]
return
fi
[ -t 0 ] || return 1
printf '%s [y/N] ' "$1" >&2
read -r _ans || _ans=
case $_ans in y | Y | yes | YES) return 0 ;; *) return 1 ;; esac
}