#!/bin/sh
set -u

usage() {
	cat <<-'EOF'
		Usage:
		  backup [ARCHIVE_TAG [COMMENT]]
		  backup -h
	EOF
}

help() {
	cat <<-'EOF'

		ARCHIVE_TAG defaults to "cronjob".
		COMMENT defaults to an empty string.

		Options:
		  -h, --help    show this message
	EOF
}

for flag in "$@"; do
	case "$flag" in
		--)
			break
			;;
		--help)
			usage
			help
			exit
			;;
		*)
			;;
	esac
done

VERBOSE_FLAG=''
while getopts 'hv' flag; do
	case "$flag" in
		h)
			usage
			help
			exit
			;;
		v)
			VERBOSE_FLAG='-v'
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))


set -x

finish() {
	STATUS=$?
	printf '\n>>>\n>>> exit status: %s\n>>>\n\n' "$STATUS" >&2
}
trap finish EXIT


export BORG_REMOTE_PATH='borg1'
export BORG_PASSCOMMAND='pass show Usurpador/borg/passphrase'
SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)"
export SSH_AUTH_SOCK

borg init -e repokey-blake2 suyin:borg/usurpador ||:
borg key export suyin:borg/usurpador ~/archive/usurpador-borg-key.txt

borg create \
	$VERBOSE_FLAG                                          \
	--exclude ~/.cache                                     \
	--stats                                                \
	--compression lzma,9                                   \
	--comment "${2:-}"                                     \
	"suyin:borg/usurpador::{hostname}-{now}-${1:-cronjob}" \
	~/

borg check \
	--verbose \
	--last 3  \
	suyin:borg/usurpador

borg prune \
	--verbose         \
	--list            \
	--keep-within=6m  \
	--keep-weekly=52  \
	--keep-monthly=24 \
	suyin:borg/usurpador

ssh suyin quota
