#!/bin/sh

userresources=$XDG_CONFIG_HOME/xresources/Xresources
usermodmap=$XDG_CONFIG_HOME/xresources/Xmodmap
sysresources=/etc/X11/xinit/.Xresources
sysmodmap=/etc/X11/xinit/.Xmodmap

# merge in defaults and keymaps

if [ -f $sysresources ]; then
  xrdb -merge $sysresources
fi

if [ -f $sysmodmap ]; then
  xmodmap $sysmodmap
fi

if [ -f "$userresources" ]; then
  xrdb -merge "$userresources"
fi

if [ -f "$usermodmap" ]; then
  xmodmap "$usermodmap"
fi

if [ -d /etc/X11/xinit/xinitrc.d ]; then
  for f in /etc/X11/xinit/xinitrc.d/?*.sh; do
    # shellcheck disable=1090
    [ -x "$f" ] && . "$f"
  done
  unset f
fi

# Remaps Capslock key to control.
# (only works for x environment - I haven't needed it for non-x yet)
setxkbmap -option ctrl:nocaps
# sets default to EURkey layout, with possibility to switch to german
# sets german layout to be default for the only pc I have with a german keyboard
# shellcheck disable=2039
if [ "$HOST" = "lidell" ] || [ "$HOSTNAME" = "lidell" ]; then
  setxkbmap -layout eu,de
else
  setxkbmap -layout de,eu
fi
# allows switching layouts with alt+space
setxkbmap -option grp:alt_shift_toggle

# Makes Capslock behave as escape - when ONLY capslock is pressed and released
# this only works when we already substitute a ctrl for caps with the lines above,
# otherwise control itself will act as escape.
# Needs xcape package installed. https://github.com/alols/xcape
# set a timeout of 500ms, if pressed longer it will ignore esc
type xcape >/dev/null 2>&1 && xcape -e 'Control_L=Escape' -t 500

# unclutter is a program to hide your mouse cursor when it is not moved
type unclutter >/dev/null 2>&1 && unclutter &
# picom is the maintained version of desktop compositor compton
type picom >/dev/null 2>&1 && picom &

# if sxhkd - the key-binding daemon is installed, start it up
type sxhkd >/dev/null 2>&1 && sxhkd-piped &

# if nextcloud-client exists, start it up
type nextcloud >/dev/null 2>&1 && nextcloud --background &

# load nm-applet, to allow easy vpn setting/switching from x interface
# TODO this should over time be replaced with a custom polybar interface
type nm-applet >/dev/null 2>&1 && nm-applet &

# additional config options for Touchpad devices ONLY
if [ "$(journalctl --dmesg -o short-monotonic --no-hostname --no-pager | grep -c "Touchpad")" -gt 0 ]; then
  # enable touch tapping for XPS13 touchpad - for different devices get the touchpad name with xinput list-prop <TAB>
  xinput set-prop "DLL075B:01 06CB:76AF Touchpad" "libinput Tapping Enabled" 1
fi

type i3 >/dev/null 2>&1 && exec i3