#! /bin/sh

#btrfs="echo btrfs"
btrfs=btrfs

if [ "$#" -ne 3 ]; then
   echo Usage $0 SUBVOL DEST KEEP
   exit 1
fi

subvol=$1
dest=$2
keep=$3

date=$(date +%Y.%m.%d-%H:%M:%S)

mkdir -p $(dirname $dest$date)

count=$(ls -d $dest* 2>/dev/null | wc -l)
if [ "$count" -ge "$keep" ]; then
    for del in $(ls -v -d $dest*  2>/dev/null | head -n $(($count - $keep + 1))); do
        $btrfs subvolume delete $del
    done
fi

$btrfs subvolume snapshot -r $subvol $dest$date

