#!/bin/sh
default="${DEFAULT_XKBMAPFILE:-dvorak.xkb}"

statefile="/tmp/current-keymap"
compiled_dir="${XDG_DATA_HOME}/xkb/compiled/"
default_file="${compiled_dir}${default}"

[ -r $statefile ] && current=$(cat $statefile) || current=""

setmap() {
	xkbcomp "$1" "$DISPLAY"
	if $notify; then
		notify-send -h string:x-dunst-stack-tag:"remaps" \
            "󰌌 Keymap set" "Layout: $(xkbcomp :0 - | grep -oP "(?<=pc[_+])([^_+]+)(?=[_+])" | tr "(" " " | head -c -2)"
	fi
	echo "$1" >"$statefile"
    xset r rate 300 50
    xset -q | grep "Caps Lock:\s*on" && xdotool key Caps_Lock
    killall xcape 2>/dev/null
    xcape -e 'Super_L=Escape'
}

rotatemap() {
	if [ "$current" = "" ]; then
		setmap "$default_file"
		return
	fi
	currentfound=false
	first=""
	for f in "${XDG_DATA_HOME}/xkb/compiled/"*; do
		if [ "$first" = "" ]; then
			first=$f
		fi
		if $currentfound; then
			setmap "$f"
			return
		elif [ "$f" = "$current" ]; then
			currentfound=true
		fi
	done
	setmap "$first"
}

notify=true
while getopts dq flag; do
	case "$flag" in
	d)
		setmap "$default_file"
		return
		;;
	q) notify=false ;;
	*) ;;
	esac
done

rotatemap

# sleep 0.03
# [ "$1" != "-n" ] && pkill -RTMIN+15 dwmblocks