#!/bin/ash
# luks helper for fatdog-drive-icon-action-handler.sh
# Copyright (C) JakeSFR (2021)
# License: GNU GPL Version 3 or later
#
# Need this file so that we can escalate to root cleanly
#
# Parameter: $1-devname (with /dev), $2-cryptpoint

dlg_wait() {
	Xdialog --title "Working" --no-buttons --infobox "Opening LUKS device, please wait ..." 0 0 10000000 &
	XPID=$!
}

##################### main #######################
# Parameter: $1-devname (with /dev), $2-cryptpoint
[ $# -lt 2 ] && exit
[ $(id -u) -ne 0 ] && exec gtksu "Opening ${1##*/}" $0 "$@"

result=$(Xdialog --stdout --title "Request" \
		--check "Use keyfile instead of a password" false \
		--password --input "Enter password for encrypted device ${1##*/}:" 0 0)
[ $? -ne 0 ] && exit

password="$(echo "$result" | head -n 1)"
checkbox="$(echo "$result" | tail -n 1)" 

if [ "$checkbox" = 'checked' ]; then
	keyfile=$(Xdialog --stdout --title "Request" \
			--backtitle "Select a keyfile for encrypted device ${1##*/}:" \
			--fselect "$HOME" 0 0)
	[ $? -ne 0 ] && exit
	dlg_wait
	result="$(cryptsetup -d "$keyfile" open "$1" "$2" 2>&1)"
else
	dlg_wait
	result="$(echo "$password" | cryptsetup open "$1" "$2" 2>&1)"
fi

EXIT_CODE=$?
kill -0 $XPID 2>/dev/null && kill $XPID

# nbd devices' icons don't refresh automatically after opening
case "$1" in
	/dev/nbd*) [ $EXIT_CODE -eq 0 ] && fatdog-drive-icon-refresh-icon.sh $1 ;;
esac

echo "$result"
exit $EXIT_CODE
