#!/bin/sh
set -eu

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

while getopts 'h' flag; do
	case "$flag" in
		h)
			usage
			help
			exit
			;;
		*)
			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:usurpador-borg ||:
borg key export suyin:usurpador-borg ~/archive/usurpador-borg-key.txt

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

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

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

ssh suyin quota
