#!/bin/sh

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

# merge in defaults and keymaps

test -f $sysresources    && xrdb -merge  $sysresources
test -f $sysmodmap       && xmodmap      $sysmodmap
test -f "$userresources" && xrdb -merge "$userresources"
test -f "$usermodmap"    && xmodmap     "$usermodmap"

# start some nice programs
SSH_AGENT=""
if [ -x /usr/bin/ssh-agent ]; then
  SSH_AGENT=/usr/bin/ssh-agent
fi

# Source /etc/profile
. /etc/profile

# --- XDG Environment Setup ---
export XDG_SESSION_TYPE=x11
export XDG_CURRENT_DESKTOP=dwm
export XDG_SESSION_DESKTOP=dwm
export DESKTOP_SESSION=dwm

# Set default XDG paths if missing
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
export XDG_RUNTIME_DIR="/run/user/$(id -u)"

test $(which xsetroot)  && xsetroot -solid midnightblue &
test $(which gpg-agent) && eval $(gpg-agent --daemon)

if [ $(which xbanish) ]; then
    xbanish >>$HOME/.xbanish.log &    # https://github.com/jcs/xbanish
elif [ $(which unclutter) ]; then
    unclutter &
fi

# source machine- and uname-specific xinitrcs
xinitcfg="$HOME/.config/xinit"
test -f "$xinitcfg/u/$(uname)"       && . "$xinitcfg/u/$(uname)"
test -f "$xinitcfg/host/$(hostname)" && . "$xinitcfg/host/$(hostname)"

# set wallpaper
feh --bg-fill --randomize /usr/share/feh/wallpaper/*

# exit X when dwmstatus (or failsafe xterm) is killed
if [ $(which dwmblocks) ]; then
    dwmblocks &
elif [ $(which dwmstatus) ]; then
    dwmstatus
elif [ $(which st) ]; then
    st
elif [ $(which urxvt) ]; then
    urxvt
elif [ $(which uxterm) ]; then
    uxterm -ls -T Failsafe -geometry 80x24-0-0
elif [ $(which rxvt) ]; then
    rxvt
elif [ $(which xterm) ]; then
    xterm -ls -T Failsafe -geometry 80x24-0-0
fi

# Activate dbus variables
dbus-update-activation-environment --all
dbus-launch $SSH_AGENT dwm-bin
