#!/bin/sh

ppid()
{
	cut -d" " -f4 /proc/$1/stat
}

case "$1" in
	pre)
		if [ "$(setting get snapshots.autoSnapshot)" = "true" -a "$2" != "update" ]; then
			dpkg_pid=$(ppid $(ppid $PPID))
			if [ "$dpkg_pid" != "$(cat /var/spool/dpkg.pid 2>/dev/null)" ] && mount | grep -q "/ type btrfs"; then
				echo $dpkg_pid > /var/spool/dpkg.pid
				mkdir -p /mnt/root
				mount $(mount | grep " / " | cut -d" " -f1) /mnt/root -o subvol=/
				usleep 100000
				snapshot="$(date +"%Y-%m-%d %H:%M")"
				action="$(tr \\0 ' ' < /proc/$dpkg_pid/cmdline | sed 's/[^ ]*//; s/\(\ -[^ ]*\)*//g')"
				if [ ! -e "/mnt/root/$snapshot" ]; then
					if grep -q " /boot " /proc/mounts; then
						cp -prf /boot/* /mnt/root/@root/boot/
						find /mnt/root/@root/boot -name ldlinux.sys -exec rm {} \;
					fi
					{ btrfs subvolume snapshot /mnt/root/@root "/mnt/root/$snapshot" && echo "auto snapshot before $action" > "/mnt/root/$snapshot/snapshotinfo"; } | sed "s/__\+//"
				else
					echo "auto snapshot before $action" >> "/mnt/root/$snapshot/snapshotinfo"
				fi
				# Delete old auto snapshots. First delete the first multiple snapshots of the same day. Than delete all but the newest 10 snapshots.
				grep -l "^auto snapshot" /mnt/root/20*/snapshotinfo 2>/dev/null | sort | while read snapshot; do if [ "${last% *}" = "${snapshot% *}" ]; then btrfs subvolume delete "${last%/*}"; break; fi; last=$snapshot; done
				grep -l "^auto snapshot" /mnt/root/20*/snapshotinfo 2>/dev/null | sort -r | tail -n +11 | while read snapshot; do btrfs subvolume delete "${snapshot%/*}"; done
				umount /mnt/root
				rmdir /mnt/root
			fi
		fi
		;;
	post)
		;;
esac
