#!/bin/bash
################################################
### Managed by someone's ansible provisioner ###
################################################
# Part of: https://git.somenet.org/root/pub/somesible.git
# 2017-2026 by someone <someone@somenet.org>
#

# Copyright 2011 by Jan Vales <jan@jvales.net> (Someone <someone@somenet.org>)
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, version 3 of the License.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program.	If not, see <http://www.gnu.org/licenses/>.
#

#
# Manage BTRFS snapshots
# 0 * * * * /root/somescripts/btrfs/snapshot.sh &> /dev/null
#

BTRFS_SNAPSHOT_DELSNAP=10

if [ -z "$BTRFS_SNAPSHOT_MAXSNAP" ]; then
    BTRFS_SNAPSHOT_MAXSNAP=13
fi

CALLPATH="`pwd`"

for fs in $(find /btrfs/ -xdev -mindepth 1 -maxdepth 1 -type d); do
    STARTTS="`date +'%Y-%m-%d--%H-%M'`"
    echo "FS: $fs -- $STARTTS"
    chmod u=rwX,go=X $fs

    if [ -e "${fs}.automount" ]; then
        mount $fs &> /dev/null
    fi
    cd $fs

    #for every .autosnap subvol...
    for vol in $(find $fs -xdev -maxdepth 1 -iname '*.autosnap'); do
        VOLNAME=`echo "${vol}" | sed -e 's/\.autosnap//' `
        echo "VOL: ${VOLNAME}"

        # delete snapshots...
        for i in $(seq -f %02g $(echo "${BTRFS_SNAPSHOT_MAXSNAP}+${BTRFS_SNAPSHOT_DELSNAP}"|bc) -1 ${BTRFS_SNAPSHOT_MAXSNAP}); do
            if [ -e "${VOLNAME}.${i}.snap" ]; then
                btrfs subvolume delete "${VOLNAME}.${i}.snap"
            fi
        done

        # move existing snapshots
        for i in $(seq -f %02g ${BTRFS_SNAPSHOT_MAXSNAP} -1 0) ; do
            if [ -e "${VOLNAME}.${i}.snap" ]; then
                mv "${VOLNAME}.${i}.snap" "${VOLNAME}.$(echo "$i"|awk '{printf "%02g",$0+1}').snap"
            fi
        done

        # create new snapshot
        touch -m -a "${VOLNAME}.autosnap"
        btrfs subvolume snapshot -r "${VOLNAME}.autosnap" "${VOLNAME}.00.snap"
    done

    cd $CALLPATH

    if [ -e "${fs}.automount" ]; then
        umount $fs &> /dev/null || echo "Failed to unmount"
    fi
done

echo "my-btrfs-cleaner: $(ps x | grep '\[btrfs-cleaner\]')" > /dev/kmsg
