#!/bin/sh

# For Debian install in late_command or in a TTY during installation.
# Complete the Btrfs partitionning
#
# Source: https://wiki.101010.fr/doku.php?id=debian:installation_btrfs

# Ensure to run the script only with a btrfs root
grep " /target btrfs " /etc/mtab || exit 1

# Remount the partition with "compress" option
mount -o remount,defaults,compress=lzo /target

# Manage subvolumes creation
for DIR in etc home opt root srv tmp usr var; do
	## Move existent directory to a temp directory
	test -d "/target/${DIR}" && mv -- /target/"${DIR}" /target/"${DIR}".temp
	## Create subvolume
	btrfs subvolume create /target/"${DIR}"
	## If the directory already existed
	if [ -d "/target/${DIR}.temp" ]; then
		## Move the content to the new subvolume
		mv -- /target/"${DIR}".temp/* /target/"${DIR}".temp/.[!.]* /target/"${DIR}".temp/..?* /target/"${DIR}"
		## Remove the temp directory
		rmdir -- /target/"${DIR}".temp
	fi
done

# Ensure everything is ok
btrfs subvolume list -p /target

exit 0