Startseite
Astronomie
Gipfelbuch
Photos
Whisky
Whiskyrechner
Passwortgenerator
Simpsons
Code
xkcd

Kleingedrucktes
Kontakt
#!/bin/bash


# make sure that the script ends with the first command that does not return zero
set -e

# in this file the information about mounted devices is stored
logfile=/tmp/lukslog

function exit_print
{
    echo $1
    exit $2

}

function choose
{   # Provides the possibility to choose one of the mounted luks devices for unmount and lock

    if [ -f $logfile ];then
       cat $logfile
    else
       exit_print "No logfile. Probably no luks-device mounted." 1
    fi
    
    read choice     # expects a number

    # extract the line of the logfile with the given number
    mapper_device=$(awk "/^${choice})/{print \$2}" $logfile)

    # catch erroneous input, i.e. empty mapper-device
    [ -z "${mapper_device}" ] && exit_print "Empty string" 1

    # make sure that the device is a block device
    [ ! -b "${mapper_device}" ] && exit_print "\"${mapper_device}\" is no block device" 1

    echo "Unmounting ${mapper_device}"
    
}

# define global varaibles
mapper_device=""
choice=""

# No argument given -> let user choose
# Argument given    -> check if a block device name was given an proceed
case "$1" in
    "") choose;;
     *) if [ -b $1 ];then
            mapper_device=$1
        else
            exit_print "Given argument is no block device" 1
        fi ;;
esac

# handle possible errors
if [ -z "$mapper_device" ];then
    exit_print "No mapper device found" 1
fi

# first, use udisk to unmount the mapper-device
udisksctl unmount -b $mapper_device

# then use udisk to lock the mapper-device and keep the name
locked_device=$(udisksctl info -b $mapper_device  | awk -F/ '/CryptoBackingDevice/{print $NF}' | tr -d \')

# adjust format
locked_device="/dev/$locked_device"

# use udisk to lock the mapper-device
udisksctl lock -b $locked_device

# in case we had a file mounted, unbind the loop device
if [[ $locked_device =~ loop[0-9] ]];then
    udisksctl loop-delete -b $locked_device
fi

# delete corresponding line in logfile
sed -i "/^${choice})/d" $logfile

# if the file is now empty: delete it
content=$(cat $logfile)

if [ -z "$content" ];then 
    rm $logfile
fi