#! /bin/bash

# Copyright © 2015 Vladimir Olteanu <vl.olteanu@gmail.com>
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# the COPYING file for more details.

set -e

DATE_FMT="%Y-%m-%d-%T"

sanity()
{
	name=$1
	root=$2
	
	if [ ! -d "$root/$name/" ]
	then
		mkdir "$root/$name/"
        fi
	
	if [ ! -d "$root/$name/current" ]
	then
		btrfs subvolume create "$root/$name/current/"
	fi
	return 0
}

snapshot()
{
	name=$1
	root=$2
	
	btrfs subvolume snapshot "$root/$name/current/" "$root/$name/$(date +"$DATE_FMT")/"
}

backup()
{
	name=$1
	root=$2
	source=$3
	
	rsync -a --delete --progress "$source/" "$root/$name/current/"
}

whole_shabang()
{
	name=$1
	root=$2
	source=$3
	
	sanity $name $root
	backup $name $root $source
	snapshot $name $root
}

if [ $# -eq 0 ]
then
	for i in $(ls /etc/butterback/targets/)
	do
		whole_shabang "$i" "/etc/butterback/root/" "/etc/butterback/targets/$i/"
		
	done
elif [ $# -eq 3 ]
then
	whole_shabang "$1" "$2" "$3"
fi

echo Done

