#!/bin/bash

already_open() {
	local dev=$1
	local cryptdev=$2
	if /sbin/cryptsetup status $cryptdev | grep -q "is active"
	then
		if /sbin/cryptsetup status $cryptdev | grep -qP "device:\s+$dev"
		then
			return 0
		fi
	fi
	return 1
}

for mountdata in /dev/shm/access/{0..9} /dev/shm/access{10..99}
do
	if ! [[ -d $mountdata ]]
	then
		break
	fi
	if [[ -f $mountdata/partuuid ]]
	then
		dev=$(blkid -t PARTUUID="$(cat $mountdata/partuuid)" -o device)
	else
		dev=$(cat $mountdata/dev)
	fi
	mountpoint=$(cat $mountdata/mountpoint)
	if [[ -z $dev ]] || [[ -z $mountpoint ]]
	then
		echo "Failed device detect" 1>&2
		exit 1
	else
		cryptdev="$(basename $dev)_crypt" 
	fi
	if [[ -f $mountdata/header ]]
	then
		headerpart="--header $mountdata/header"
	fi
	if ! already_open $dev $cryptdev
	then
		/sbin/cryptsetup $headerpart -d $mountdata/key luksOpen $dev $cryptdev
		res=$?
		if [[ $res -ne 0 ]]
		then
			exit $res
		fi
	fi
	echo "/sbin/cryptsetup luksClose $cryptdev"

	mount /dev/mapper/${cryptdev} $mountpoint
	res=$?
	if [[ $res -ne 0 ]]
	then
		exit $res
	fi
	echo "/bin/umount $mountpoint"
done | tac >/dev/shm/access/stop
res=${PIPESTATUS[0]}
chmod 700 /dev/shm/access/stop
exit $res
