From e28da8c390de3386eb71e651c5c4491ceaf4990a Mon Sep 17 00:00:00 2001
From: LeLutin <gabster@lelutin.ca>
Date: Fri, 14 Aug 2020 05:46:34 -0700
Subject: [PATCH] borg: add configuration to displace the cache directory

borg will by default create its cache directory in ~/.cache/borg. This
means that during backup runs, borg will read and write quite
extensively from/to this directory.

In some situations, it is rather undesirable to have this amount of IO
activity in this location and it would make sense to tell borg to place
its cache elsewhere. This can help for example with placing the cache on
a hard drive where the added IO load will not have as big of an impact
on other running activity for the system.

This change also makes sure that the cache directory environment
variable is cleared out when the configuration option is unset. This
should avoid unpleasant surprises when this environment variable is set
to some unknown value in the context where backupninja is called, which
could lead to borg reading and writing to random places on the system.
---
 examples/example.borg |  6 ++++++
 handlers/borg.in      | 15 +++++++++++++++
 2 files changed, 21 insertions(+)

diff --git a/examples/example.borg b/examples/example.borg
index b49598d..4988e9c 100644
--- a/examples/example.borg
+++ b/examples/example.borg
@@ -180,3 +180,9 @@ exclude = /var/lib/mysql
 ##
 ## Default:
 # passphrase =
+
+## Path to the directory that will hold borg's cache files. By default this is
+## empty, which will let borg use its default path of "~/.cache/borg".
+##
+## Default:
+# cache_directory =
diff --git a/handlers/borg.in b/handlers/borg.in
index df500a8..0ca5cb0 100644
--- a/handlers/borg.in
+++ b/handlers/borg.in
@@ -31,6 +31,7 @@ getconf create_options
 getconf prune yes
 getconf keep 30d
 getconf prune_options
+getconf cache_directory
 
 setsection dest
 getconf user
@@ -56,6 +57,20 @@ else
 fi
 execstr_archive="$archive"
 
+if [ -n "$cache_directory" ]; then
+   cache_parent_dir=$(dirname "$(readlink -f "$cache_directory")")
+   [ -d "$cache_parent_dir" ] || fatal "Cache directory parent dir '$cache_parent_dir' is absent or is not a directory."
+   BORG_CACHE_DIR=$cache_directory
+   export BORG_CACHE_DIR
+else
+   # Cache dir not set, let's clear out the environment variable to avoid
+   # having this directory be pointed to a random destination.
+   # Also apparently if we set the variable to an empty string, borg uses the
+   # empty string as though it was some path we specified and backup runs
+   # error out, so we need to unset the variable completely.
+   unset BORG_CACHE_DIR
+fi
+
 # check the connection at the source and destination
 [ -n "$test" ] || test=0
 if [ "$host" != "localhost" ] && ([ "$testconnect" = "yes" ] || [ "${test}" -eq 1 ]); then
-- 
GitLab