#!/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 2018 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/>.
#

#
# Regenerate /home/$user/.btrfs-snapshots/ symlinks
# we use relative symlinking in order to break infinite recursions.
#

cd /home/
for home in $(find . -xdev -mindepth 1 -maxdepth 1 -type d); do
    echo "HOME: /home/${home}"
    rm -rf "/home/${home}/.btrfs-snapshots"
    mkdir "/home/${home}/.btrfs-snapshots"

    cd "/btrfs/"
    for snap in $(find . -mindepth 2 -maxdepth 2 -type d -iname 'home.*.snap'); do
        snap_name=$(echo -n $snap | sed -E -e 's#/#-#2g')
        ln -snf "../../../btrfs/${snap}/${home}" "/home/${home}/.btrfs-snapshots/$snap_name"
        touch -ahm -r "/btrfs/${snap}" "/home/${home}/.btrfs-snapshots/$snap_name"
    done

    rename -v 's/home\.(.*)\.snap/$1/' /home/${home}/.btrfs-snapshots/*
done
