#!/usr/bin/env bash
# backtick -- enable/disable Alt+Backtick handling in GNOME Shell
#
# In situations where a game uses the same keypress to open its "console".

. lib.bash || exit

state=$path_data/backtick.state.sh

declare -i is_disabled=0
declare -- schema=
declare -- key=
declare -- value=

if [[ -f "$state" ]]; then
	. "$state" || rm -f "$state"
fi

if (( is_disabled )); then
	debug "already disabled according to state; re-setting original values"
	debug " - schema = $schema"
	debug " - key = $key"
	debug " - value = \"${value}\""
	is_disabled=0
	gsettings set "$schema" "$key" "$value"
else
	debug "currently enabled; searching for matching settings"
	schema="org.gnome.desktop.wm.keybindings"
	unset key
	unset value
	re="'<Alt>Above_Tab'"
	while read -r r_schema r_key r_value; do
		if [[ $r_value == *$re* ]]; then
			debug "probably found a match"
			debug " - schema = $r_schema"
			debug " - key = $r_key"
			debug " - value = $r_value"
			schema=$r_schema
			key=$r_key
			value=$r_value
		fi
	done < <(gsettings list-recursively "$schema")
	if [[ $schema && $key && $value ]]; then
		new_value=${value//"$re"/}
		new_value=${new_value//"[, "/"["}
		new_value=${new_value//", ]"/"]"}
		is_disabled=1
		gsettings set "$schema" "$key" "$new_value"
	else
		die "could not find apropriate setting"
	fi
fi

declare -p is_disabled schema key value > "$state"

case $is_disabled in
	1) status="disabled"; icon="system-lock-screen";;
	0) status="enabled"; icon="preferences-desktop-keyboard-shortcuts";;
esac

if [[ -t 1 ]]; then
	echo "Alt+Backtick has been $status."
else
	notifysend -r hotkey -e -i "$icon-symbolic" \
		"Alt+Backtick" \
		"Alt+Backtick has been $status."
fi
