Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

bup-vw.sh (Source)

#!/bin/sh
# File: vm4:/home/vaultwarden/bup-vw.sh
# Location: vm4
# Author: bgstack15
# Startdate: 2023-01-02-2 16:54
# Title: Bup Vaultwarden
# Project: bup-vw
# Purpose: Backup Vaultwarden contents
# History:
# Usage: called by cron: 70_vaultwarden_cron
# Reference:
#    https://github.com/dani-garcia/vaultwarden/wiki/General-%28not-docker%29
#    photorprism/bup-pp-db.sh
# Improve:
# Dependencies:
#    sudo access for user vaultwardern to run bup-vw-db.sh, /etc/sudoers.d/70_vaultwarden_bup_sudo
# Documentation:
#    README-vw-bup.md
workdir="$( dirname "$( readlink -f "${0}" 2>/dev/null )" 2>/dev/null || echo "${PWD}" )"
#echo "workdir=${workdir}"
test -z "${CONFFILE}" && CONFFILE="${workdir}/bup-vw.conf"
test -e "${CONFFILE}" && . "${CONFFILE}"
test -z "${LOGFILE}" && LOGFILE="/mnt/public/Support/Systems/vm4/var/log/vaultwarden/bup-vw.$( date "+%F" ).log"
_return() {
   return ${1}
}
main() {
   export OUTDIR=/mnt/public/Support/Systems/vm4/vw/vaultwarden
   export LOCALOUTDIR=/home/vaultwarden/bup
   export OUTFILE="${LOCALOUTDIR}/vw.$( date "+%F" ).sq3"
   export OUTTARBALL="${OUTDIR}/vw.$( date "+%F" ).tgz"
   # fail early if network mount is not there
   if ! test -w "$( dirname "${OUTFILE}" )" ;
   then
      echo "Fatal! Unable to write to directory for ${OUTTARBALL}: Aborted."
      exit 1
   fi
   # run the bup-vw-db.sh script, collect other things, make a tarball
   generated_file="$( sudo /home/vaultwarden/bup-vw-db.sh )"
   if ! test -f "${generated_file}" ;
   then
      echo "Fatal! Unable to find exported database file ${OUTFILE}: Aborted."
      exit 1
   fi
   relative_generated_file="bup/$( basename "${generated_file}" )"
   tar -zcf "${OUTTARBALL}" -C /home/vaultwarden vw/docker-compose.yml vw/.env vw/bitwarden "${relative_generated_file}"
   find "${OUTTARBALL}"
}
# Determine if this script was dot-sourced
sourced=0
if [ -n "$ZSH_EVAL_CONTEXT" ]; then
  case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
  [ "$(cd $(dirname -- $0) && pwd -P)/$(basename -- $0)" != "$(cd $(dirname -- ${.sh.file}) && pwd -P)/$(basename -- ${.sh.file})" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
  (return 0 2>/dev/null) && sourced=1
else # All other shells: examine $0 for known shell binary filenames
  # Detects `sh` and `dash`; add additional shell filenames as needed.
  case ${0##*/} in sh|dash) sourced=1;; esac
fi
# So, if not dot-sourced, and this is run by cron, add logging
if test $sourced -eq 0;
then
   if echo " ${@} " | grep -q cron ;
   then
      main 2>&1 | plecho | tee -a "${LOGFILE}"
      response=$?
      printf '\n' | tee -a "${LOGFILE}"
   else
      main
      response=$?
   fi
fi
_return ${response}