#!/usr/bin/env bash

. lib.bash || exit

_die() {
	zenity --error --title "" --text "$*"
	die "$*"
}

path="$HOME/Private"
dpath=${path/#${HOME%/}'/'/'~/'}
lock="$HOME/.ecryptfs/Private.mnt"

if [[ $1 == "--nowait" ]]; then
	exec {fd}<"$lock" && flock -x -n $fd ||
		die "another unlock prompt already running"
else
	if mountpoint -q "$path"; then
		info "$dpath already mounted, exiting"
		exit 0
	else
		exec {fd}<"$lock" || exit 1
		# display unlock prompt if none running
		flock -x -n $fd && {
			flock -u $fd
			ecryptfs-mount-x11 --nowait
		}
		# wait for unlock
		exec flock -x $fd || exit 1
	fi
fi

pw=$(zenity --entry \
	--title "Unlock private files" \
	--text "Your private directory is locked.\n\nEnter password for $dpath" \
	--hide-text \
	--ok-label "Unlock" \
) || exit 1

wrapped=~/.ecryptfs/wrapped-passphrase

# Twice. Sometimes it "forgets" to insert the FNEK. Fucker.
printf '%s' "$pw" | ecryptfs-insert-wrapped-passphrase-into-keyring "$wrapped" - ||
	_die "Failed to unlock your private files."
#printf '%s\n' "$pw" | ecryptfs-insert-wrapped-passphrase-into-keyring "$wrapped" - ||
#	_die "Failed to unlock your private files."
ecryptfs-mount-private </dev/null ||
	_die "Failed to mount $dpath."
