#!/bin/sh

# Vars {{{
[ -z "${DEBUG}" ] && readonly DEBUG=0
## Export DEBUG for sub-script
export DEBUG

## Define the hard drive to use
if [ -b '/dev/sda' ]; then
	hdd="/dev/sda"
else
	printf '%b\n' "Please check the hard drive to use"
	exit 0
fi

## Try to guess the VG name by using the last VG detected
vgname=$(vgdisplay --short | tail -n 1 | sed 's/.*"\(.*\)" .*/\1/')
# }}}

debug_message() {                                               # {{{

	local_message="${1}"

	## Print message if DEBUG is enable (=0)
	[ "${DEBUG}" -eq "0" ] && printf '\e[1;35m%-6b\e[m\n' "DEBUG − ${PROGNAME}: ${local_message}"

	return 0
}
# }}}

# Umount filesystems {{{

mountpoint -q /target/boot       && umount -- /target/boot

mountpoint -q /target/home       && umount -- /target/home
mountpoint -q /target/opt        && umount -- /target/opt
mountpoint -q /target/srv        && umount -- /target/srv
mountpoint -q /target/tmp        && umount -- /target/tmp
mountpoint -q /target/usr        && umount -- /target/usr
mountpoint -q /target/var        && umount -- /target/var

mountpoint -q /target/srv/backup && umount -- /target/srv/backup
mountpoint -q /target/var/lib/vz && umount -- /target/var/lib/vz

swapoff /dev/mapper/"${vgname}"-swap > /dev/null 2>&1

mountpoint -q /target/dev        && umount /target/dev
mountpoint -q /target/dev/pts    && umount /target/dev/pts
mountpoint -q /target/proc       && umount /target/proc
mountpoint -q /target/sys        && umount /target/sys
mountpoint -q /target/run/lvm    && umount /target/run/lvm
mountpoint -q /target/run/udev   && umount /target/run/udev

mountpoint -q /target            && umount -- /target
# }}}

## Disable LVM {{{
### Disable LVM devices
vgchange --activate n --quiet > /dev/null

## }}}
## Is LUKS {{{
if blkid | grep -q -- "${hdd}.*crypto_LUKS"; then
	debug_message "is_luks − \
Luks seems available on ${hdd} device."
	manage_luks=0

	luks_pv_name=$(basename "${hdd}"2_crypt)
else
	manage_luks=1
	debug_message "is_luks − \
No Luks system on ${hdd} device."
fi

## }}}
## Close LUKS device {{{
if [ "${manage_luks}" -eq 0 ]; then
	### If the volume is opened
	if [ -h /dev/mapper/"${luks_pv_name}" ]; then
		debug_message "close_luks − \
Try to close Luks on ${luks_pv_name} − ${hdd}2"
		### Close LUKS device
		cryptsetup luksClose "${luks_pv_name}" || exit 2
	fi
fi
## }}}

exit 0