#! /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/>.

SRC="/usr/libexec/ykocli"

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

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

source "$SRC/src-yko-devinfo.sh"
if [[ $? -ne 0 ]]; then
	exit $?
fi

firmware_level=${device_info[device_index]%)*}
firmware_level=${firmware_level#*(}
firmware_level=${firmware_level//./}
key_serial=${device_info[device_index]##*Serial:}

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

if [[ $? -eq 0 ]]; then
	source "$SRC/src-yko-ck-touch.sh"
	
	if [[ $touch_em == "YES" ]]; then
		:
	else
		ykman -d $key_serial oath accounts code $search_string > $ykman_table
		mapfile -t <  "$ykman_table"

		if ! [[ -s $ykman_table ]]; then
			source "$SRC/src-yko-figlet.sh"
			printf "${CWARN}No matching entry found on YubiKey\n"
			printf "${CINFO}You searched for ${CARROW}====> ${CINFO}$search_string\n"
			printf "${CALERT}Exiting.\n"
			printf "${RESTORE}\n"
			exit 2
		fi
	fi
fi

case $ACTION in

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

	"TOTP"	)
	if [[ $touch_em == "YES" ]]; then
		:
	else
		source "$SRC/src-yko-table.sh"
	fi
	source "$SRC/src-yko-totp.sh";;

	"ADD"	)
	source "$SRC/src-yko-add.sh"
	if [[ $? -eq 0 ]]; then
		from_src_yko_add="YES"
		source "$SRC/src-yko-totp.sh"
	fi;;

	"DELETE"	)
	source "$SRC/src-yko-table.sh"
	source "$SRC/src-yko-delete.sh";;

	"RENAME"	)
	source "$SRC/src-yko-table.sh"
	source "$SRC/src-yko-rename.sh";;

esac

exit
