#!/bin/bash
# barium helper scripts
# author: rosalinux.ru: betcher_
export TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN=rosa-rw_functions
export PATH=${PATH}:/usr/lib/rosa-rw/scripts:/sbin:/usr/sbin:/bin:/usr/bin

MSG01="$(gettext -s "Mount the encrypted partition on this machine automatically?")"
MSG02="$(gettext -s "OK")"
MSG03="$(gettext -s "Your computer has been added to trusted")"
MSG04="$(gettext -s "Cancel")"
MSG05="$(gettext -s "the password may be incorrect ")"
MSG06="$(gettext -s "Slots avaliable")"
MSG07="$(gettext -s "To continue the boot process, you must add this machine to the list of trusted")"
MSG08="$(gettext -s "Enter the password for the encrypted partition again")"
MSG09="$(gettext -s "Password for the encrypted partition")"
MSG10="$(gettext -s "LUKS password")"
MSG11="$(gettext -s "Try on next boot")"
MSG12="$(gettext -s "Successfully")"
MSG13="$(gettext -s "Error")"
MSG14="$(gettext -s "The password may be incorrect.\nOr the key for the current machine is missing.")"
MSG15="$(gettext -s "Cannot find encrypted partition ")"
MSG16="$(gettext -s "Attantion")"

HLP() {
echo "$(basename $0):"
echo "Утилита для добавления/удаления ключей LUKS шифрованного раздела OC barium,"
echo "привязанных к характеристикам машины пользователя"
echo "Использование:" 
echo "	$(basename $0) addKey		- добавить ключ сгенерированный для текущей машины в слот LUKS"
echo "	$(basename $0) rmCurrent 	- удалить ключ текущей машины"
echo "	$(basename $0) rmAll		- удалить все ключи кроме первого"
echo "	$(basename $0) firstTime	- для автозапуска во время загрузки машины"
echo "	$(basename $0) (-h | --help)	- эта справка"
exit
}

[ "$1" == '--help' -o "$1" == '-h' ] && HLP

EXITCMD="poweroff -f"
LUKSSLOTS=8

. /usr/lib/rosa-rw/os-config
. /etc/ROSA-RW/config

BUSYBOX=busybox
which $BUSYBOX >/dev/null 2>&1 || BUSYBOX=busybox.static

getSlots() {
    enabled=$(cryptsetup luksDump "$1" | egrep "^[[:space:]]+[[:digit:]]+:[[:space:]]+luks" |wc -l)
    echo $(( "$LUKSSLOTS" - "$enabled" ))
}

addKey() {
    SLOTS=$(getSlots $DEVICE)
    HARDPASS=$($BUSYBOX lspci |md5sum |cut -f1 -d ' ')
    mdialog --yesno "${MSG01}\n${MSG06}: $SLOTS"
    [ $? != 0 ] && exit
    PASS=$(mdialog --inputbox "$MSG09" password)
    [ -z "$PASS" -o "$PASS" == "password" ] && exit
    echo -e "${PASS}\n${HARDPASS}" | cryptsetup luksAddKey $DEVICE --force-password 
    if [ $? == 0 ] ; then
	SLOTSNOW=$(getSlots $DEVICE )
	echo "$SLOTS -- $SLOTSNOW"
	echo "${SN}" > /home/$(xuserrun whoami)/.trusted
	[ "$SLOTS" -gt "$SLOTSNOW" ] &&   mdialog --msgbox "${MSG03}\n${MSG06}: $SLOTSNOW"
	exit
    fi
    mdialog --error "$MSG13, $MSG05"
}

firstTime() {
	export LC_ALL=ru_RU.UTF-8
	export LC_MESSAGES=ru_RU.UTF-8
	SLOTS=$(getSlots $DEVICE)
	HARDPASS=$($BUSYBOX lspci |md5sum |cut -f1 -d ' ')
	xuserrun zenity --question --width 400 --ok-label "$MSG02" --cancel-label "$MSG04" --text="${MSG07}.\n${MSG06}: $SLOTS" --title "$MSG16"
	#mdialog --yesno "${MSG07}.\n${MSG06}: $SLOTS "
	[ $? != 0 ] && $EXITCMD
	[ $SLOTS -lt 1 ] && $EXITCMD
	while [ -z "$PASS" ] ; do
	    PASS=$(xuserrun zenity --password --width 400 --ok-label "$MSG02" --title "$MSG10")
	    #PASS=$(mdialog --password "$MSG08" password)
	done
	echo -e "${PASS}\n${HARDPASS}" | cryptsetup luksAddKey $DEVICE --force-password 
	if [ $? == 0 ] ; then
		SLOTSNOW=$(getSlots $DEVICE)
		echo "$SLOTS -- $SLOTSNOW"
		for a in $(ls -1 /home) ; do
			echo "${SN}" > /home/$a/.trusted
		done
		# xuserrun zenity --info --width 400 --ok-label "$MSG02" --text="${MSG03},\n${MSG06}: $SLOTSNOW"
		#mdialog --msgbox "${MSG03},\n${MSG06}: $SLOTSNOW"
		[ "$SLOTS" -gt "$SLOTSNOW" ] && return 0 
		return 1
	fi 
	mdialog --error "${MSG13}! ${MSG05}\n${MSG11}"
	$EXITCMD
}

rmAll() {
    PASS=$(mdialog --password "$MSG09" password)
    rm -f /home/$(xuserrun whoami)/.trusted
    for a in $(seq 1 "$LUKSSLOTS") ; do
	echo -e "${PASS}" | cryptsetup  luksKillSlot $DEVICE $a
    done
    SLOTS=$(getSlots $DEVICE)
    mdialog --msgbox "${MSG06}: $SLOTS"
}

rmCurrent() {
    SLOTS=$(getSlots $DEVICE)
    HARDPASS=$($BUSYBOX lspci |md5sum |cut -f1 -d ' ')
    echo -e "${HARDPASS}" | cryptsetup  luksRemoveKey $DEVICE
    if [ $? == 0 ] ; then
	SLOTSNOW=$(getSlots $DEVICE)
	sed -i '/'${SN}'/d' /home/$(xuserrun whoami)/.trusted
	[ "$SLOTSNOW" -gt "$SLOTS" ] &&   mdialog --msgbox "${MSG12}!\n${MSG06}: $SLOTSNOW"
	exit
    fi
    mdialog --error "$MSG13, $MSG14"
}

DEVICE=$(grep '/dev/mapper/sd' /proc/mounts |awk '{print $1}' | sed 's:/mapper::' |head -n1)
[ -z "$DEVICE" ] && DEVICE=$(blkid |grep -i crypto_luks |cut -f1 -d ':' |head -n1)
[ -z "$DEVICE" ] && mdialog --error "$MSG13, $MSG15"
[ -z "$DEVICE" ] && exit 1
SN=$(udevadm info -a -p  $(udevadm info -q path -n $DEVICE) |grep serial |head -n1 |cut -f3 -d '=')
luksVersion=$(cryptsetup luksDump "$DEVICE" | grep Version |awk '{print $2}')
if [ "$luksVersion" -eq 1 ] ; then
    [ "$LUKSSLOTS" -gt 8 ] && LUKSSLOTS=8
fi

case $1 in
    "firstTime" ) firstTime ;;
    "addKey" ) 	addKey ;;
    "rmAll" ) 	rmAll ;;
    "rmCurrent" ) rmCurrent ;;
esac




