#!/usr/bin/env bash # # made by Dennis Eriksen in 2019. Gitified in 2020. # Exit on error. Append "|| true" if you expect an error. set -o errexit # Exit on error inside any functions or subshells. set -o errtrace # Do not allow use of undefined vars. Use ${VAR:-} to use an undefined VAR set -o nounset # Catch the error in case mysqldump fails (but gzip succeeds) in `mysqldump |gzip` set -o pipefail function die { echo $@ exit 1 } function main { # Check if $1 exists [[ "${1:-}" == "" ]] && die "You need to set the name of the machine you want to rebuild." local NAME=${1} # Check if mkosi-template exists, and cd into it if it does [[ -d /srv/mkosi/${NAME} ]] || die "/srv/mkosi/${NAME} does not exist" cd /srv/mkosi/"${NAME}" mkosi -o "/var/lib/machines/${NAME}.new" # Stop machine if it is running if machinectl status "${NAME}" >/dev/null; then machinectl stop "${NAME}" fi cd /var/lib/machines if [[ -e "${NAME}" ]]; then mv "${NAME}" .backup/ rm -f "${NAME}.nspawn" fi mv "${NAME}.new" "${NAME}" mv "${NAME}.new.nspawn" "${NAME}.nspawn" echo "Done building." echo "" sleep 1 echo "Starting" machinectl start "${NAME}" sleep 2 machinectl if [[ -e ".backup/${NAME}" ]]; then echo "" echo "Now zipping up the old machine, for backup" cd .backup tar c "${NAME}" | xz -0 - > "/var/lib/machines/.backup/${NAME}.tar.xz.$(date +%Y%m%d%H%M%S)" rm -r "${NAME}" cd .. fi } main $@