#!/bin/sh
# Backup linux system and user files with borg
root="/"
args="--progress --stats"
while test $# -gt 0; do
  case "$1" in
    (-n) run="arg-test"; shift;;
    (--dry-run) args="--dry-run --list"; name=test-$(date +%s); shift;;
    (--root) shift; root="$1"; name="$(basename "$(realpath "$root")")"; echo $root $name; shift;;
    (-*) name="${1#-}"; shift;;
    (*) break;;
  esac
done
test $# -gt 0 || cd "$root"
name="::$(test -n "$name" && echo "$name" || cat /etc/hostname)_${1:-system}_$(date -u +"%y%m%d")"
echo "Backing up as $name"
${run:-sudo --preserve-env=BORG_REPO BORG_PASSPHRASE="$($BORG_PASSCOMMAND)" borg} create --exclude-caches $args \
  $(echo $DIRS_IGNORE_SAFE -x 'software-challenge/**/build' -x state/emacs -x state/go -x .local/lib -x .cpan -x *cache |
    sed 's|-x \([^ ]\+\)|-e sh:**/\1|g') \
  "$name" $(test $# -eq 0 && echo etc home root || test $# -eq 1 && echo $1) "${@:2}"  2>&1
test -n "$run" || sudo chown -R $USER:$USER "$BORG_REPO"