# Pop up a message, for long running commands
command -v notify-send >/dev/null &&
	alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(echo "$history[$HISTCMD]" | sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

if which jrnl >/dev/null; then
	alias j='jrnl'
	jn() { jrnl -to today "$@" | less +G; }
	compdef jn=jrnl
	alias jnc='jn -contains'
	alias jne='jrnl --edit'
	# TODO jump to end
fi

test "$DISPLAY" || return 0

alias graphics='lspci -vnn | grep VGA --color=never && xrandr --listproviders'

# WIP Edit mozilla config
mozedit() (
	set -eo pipefail
	file="$1"
	tmpfile="/tmp/$(basename $1).tmp"
	unsetopt multios # https://stackoverflow.com/a/58261480
	# ( [[ -t 0 ]] && echo 'STDIN is attached to TTY' ) || cat
	{ echo -en '\x02\x21\x4C\x18TT\x0\x0' && dd if="$file" bs=1 skip=12 } 2>&1 >"$tmpfile" | head -1 | cut -d+ -f1 | xargs printf "%04x\n" | read len
	tmpfile2="${tmpfile}2"
	cat "$tmpfile" | sed "s/TT/\\x${len:2:2}\\x${len:0:2}/" | unlz4 >"$tmpfile2"
	cat "$tmpfile2" | sed "$2" | lz4 -l | dd bs=1 skip=8 seek=12 of="$file" conv=notrunc
)

test "$XDG_CURRENT_DESKTOP" = "KDE" || return 0

# Fix errors regarding broken mim database
alias fixmime='sudo rm /usr/share/mime/packages/kde.xml && sudo update-mime-database /usr/share/mime'

# Switch theme across system: KDE, Konsole, taskwarrior, bat
# WIP: Emacs, Mozilla, diffr (git pager)
theme_save="$XDG_CACHE_HOME/theme"
#theme_default="$(d=$(date +%H) && test $d -gt 7 && test $d -lt 19 && echo light || echo dark)"
theme_default="dark"
theme() {
	theme="$1"
	if test "$2" = "kde"
	then kcmshell5 kcm_lookandfeel
	elif test "$theme" != "$THEME" -a "$2" != "q"
	then kcmshell5 kcm_lookandfeel &
		# TODO theme diffr rather than disabling it
		bak $XDG_CONFIG_HOME/git/diffr
		emacsclient -e "(toggle-theme \"$theme\")"
	fi
	# TODO kitty
	export THEME="$theme"
	echo "$theme">"$theme_save"

	#mozfile=$(find $HOME/.mozilla/firefox/ -maxdepth 2 -name addonStartup.json.lz4 | grep ".test")
	case "$theme" in
		(light)
			# LESS_TERMCAP_DEBUG=true man man
			export LESS_TERMCAP_md=$'\e[1;34m'	# bold blue
			export BAT_THEME="OneHalfLight"
			konsoleprofile colors="Light"
			#sed -i 's/#\(include.*\/light-256.theme\)/\1/' "$XDG_CONFIG_HOME/task/taskrc"
			#mozedit $mozfile '/light@mozilla/,/"enabled"/ s/\("enabled":.*\)false/\1true/; /dark@mozilla/,/"enabled"/ s/\("enabled":.*\)true/\1false/'
			;;
		(dark)
			export BAT_THEME="OneHalfDark"
			konsoleprofile colors="Breeze"
			#sed -i 's/^include.*light-256.theme/#\0/' "$XDG_CONFIG_HOME/task/taskrc"
			#mozedit $mozfile '/light@mozilla/,/"enabled"/ s/\("enabled":.*\)true/\1false/; /dark@mozilla/,/"enabled"/ s/\("enabled":.*\)false/\1true/'
			;;
	esac
}
export THEME=$(cat "$theme_save" 2> /dev/null)
export THEME=${THEME:-$theme_default}
theme $THEME
