From 75591ce5af30213e51c256944be1696050cde592 Mon Sep 17 00:00:00 2001 From: Ohad Livne Date: Wed, 4 Jun 2025 22:44:52 +0300 Subject: [PATCH] Regularly back up Documents/ and some configuration files --- .config/setup/crontab | 1 + .local/bin/dirtree-changed | 52 ++++++++++++++++++++++++++++++++++++++ .local/bin/make-backup | 22 ++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100755 .local/bin/dirtree-changed create mode 100755 .local/bin/make-backup diff --git a/.config/setup/crontab b/.config/setup/crontab index 1d20f29..a52cfe8 100644 --- a/.config/setup/crontab +++ b/.config/setup/crontab @@ -1 +1,2 @@ @hourly /home/ohad/.local/bin/update-weather +@hourly /home/ohad/.local/bin/make-backup diff --git a/.local/bin/dirtree-changed b/.local/bin/dirtree-changed new file mode 100755 index 0000000..3220477 --- /dev/null +++ b/.local/bin/dirtree-changed @@ -0,0 +1,52 @@ +#! /usr/bin/python3 + +from pathlib import Path + + +def get_subtree_mtime(root: str | Path) -> float: + from itertools import chain + from os import walk + from os.path import getmtime + + maxtime = 0 + + for dirname, _, filenames in walk(root): + dirpath = Path(dirname) + maxtime = max( + chain( + [maxtime, getmtime(dirpath)], + (getmtime(dirpath / filename) for filename in filenames), + ) + ) + + return maxtime + + +def tree_changed_p(root: str | Path, check_file: str | Path) -> bool: + from os.path import getmtime + + try: + filetime = getmtime(check_file) + except FileNotFoundError: + return True + + return get_subtree_mtime(root) > filetime + + +if __name__ == "__main__": + import argparse + import sys + + parser = argparse.ArgumentParser(description="Manage the desktop containers") + + parser.add_argument("--directory", required=True, help="Directory tree to check") + parser.add_argument( + "--check-file", required=True, help="Timestamp file for comparison" + ) + + args = parser.parse_args() + + if tree_changed_p(root=args.directory, check_file=args.check_file): + sys.exit(0) + else: + sys.exit(1) diff --git a/.local/bin/make-backup b/.local/bin/make-backup new file mode 100755 index 0000000..cf9262f --- /dev/null +++ b/.local/bin/make-backup @@ -0,0 +1,22 @@ +#! /usr/bin/sh + +export BORG_REPO="/media/backup/" +export BORG_PASSCOMMAND="cat ${HOME}/.keys/borg-passphrase.txt" + +TS_DIR="${HOME}/.local/state/backup" + +mkdir -p "${TS_DIR}" + +backup () { + target=$1 + directory=$2 + + if "${HOME}/.local/bin/dirtree-changed" --directory "${directory}" --check-file "${TS_DIR}/${target}" + then + borg create --compression auto,lzma ::"${target}"-{now} "${directory}" + touch "${TS_DIR}/${target}" + fi +} + +backup circuits "${HOME}/.config/circuits" +backup documents "${HOME}/Documents"