#!/bin/sh

set -e
# set -x

TODAY=$(date +%Y.%m.%d_%H%M)

usage()
{
	cat <<EOF
Description:
	Backup Swift rings

Usage:
	$0 <cluster-name>

Options:
	-h: show this help menu
EOF

	exit 1
}

while getopts "h" o; do
	case "${o}" in
		h)
			usage
			;;
		?)
			echo "Invalid option" && exit 1
			;;
	esac
done
shift $((OPTIND-1))

if [ -z "${1}" ]; then
	usage
fi

LOCAL_RING_PATH="/var/lib/oci/clusters/${1}/swift-ring"
BACKUP_PATH="/var/backups/oci/clusters/${1}/swift/rings"

# make sure we have ring
if ! [ -d ${LOCAL_RING_PATH} ]; then
	echo "ERROR: Swift ring directory does not exist"
	exit 1
fi

# prepare backup destination folder
if ! [ -d ${BACKUP_PATH} ]; then
	mkdir -p ${BACKUP_PATH}
fi

# backup all available ring types
for ring in $(ls ${LOCAL_RING_PATH}/ | grep -E '^(account|container|object).*?\.builder'); do
	cp ${ring}* ${BACKUP_PATH}/${TODAY}.${ring}
done
