#! /usr/bin/bash
#
# Copyright © 2022 Gerald B. Cox
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

if [ -f "$HOME/.ykocli.conf" ]; then
	source "$HOME/.ykocli.conf"
else
	source "/etc/ykocli.conf"
fi

trap "source $SRC/src-yko-trap.sh" EXIT

source "$SRC/src-yko-set-colors.sh"

device_info=$(ykman list)

if [[ $device_info == "" ]]; then
	printf "${RED}%sValid YubiKey needs to be properly detected\n"
	printf "${RED}%sThis script will now exit.\n"
	printf "${RESTORE}\n"
	exit
fi

ck_index="^[0-9]+$"
BKGND="NO"
ykman_table="$(mktemp)"
name_search=$1
start="1"

source "$SRC/src-yko-ck-input.sh"

ykman oath accounts code $name_search > $ykman_table

if ! [[ -s $ykman_table ]]; then
	source "$SRC/src-yko-figlet.sh"
	printf "${LCYAN}No matching entry found on YubiKey\n"
	printf "${LCYAN}You searched for ====> ${LGREEN}$name_search\n"
	printf "${LCYAN}This script will now exit.\n"
	printf "${RESTORE}\n"
	exit
fi

if [[ $BKGND == "YES" ]]; then
while :
do
	source "$SRC/src-yko-main.sh"
	printf "\n${LCYAN}Returning to background mode.${LRED}\n"
	read -p "Press ENTER to exit." -t $EXITIME exit_string
	exit_code=$?
	printf "${RESTORE}"
	
	if  [[ $exit_code -gt 128 ]]; then
		qdbus-qt5 org.kde.kglobalaccel /component/konsole invokeShortcut "Konsole Background Mode"
	else
		exit
	fi

	printf "${RESTORE}"

done

else
	source "$SRC/src-yko-main.sh"
fi

exit
