#!/bin/bash

# output to syslog and stderr
# with PID and syslog identity 'wayfire'
exec 1> >(logger --id=$$ --stderr --tag wayfire) 2>&1

# if undefined, or empty, set to freedesktop specification defaults
[ -z "$XDG_DATA_DIRS" ] && export XDG_DATA_DIRS="/usr/local/share:/usr/share"

# Set the XDG_RUNTIME_DIR if we can not get it in systems
# without systemd.
if [ -z "${XDG_RUNTIME_DIR}" ]; then
  if [ -d "/run/user" ]; then
    XDG_RUNTIME_DIR="/run/user/$(id -ru)"
    export XDG_RUNTIME_DIR
  else
      if [ -d "/var/run/user" ]; then
        XDG_RUNTIME_DIR="/var/run/user/$(id -ru)"
        export XDG_RUNTIME_DIR
      else
        XDG_RUNTIME_DIR="/tmp/${USER}-runtime"
        export XDG_RUNTIME_DIR
      fi
  fi
fi

# freedesktop specifications mandate that the definition
# of XDG_SESSION_TYPE should be respected
export XDG_SESSION_TYPE=wayland
export GDK_BACKEND=wayland
export QT_QPA_PLATFORM=wayland
# In some OS the wayland backend for clutter does not work, so
# use the safe "gdk" backend instead
export CLUTTER_BACKEND=gdk
#export SDL_VIDEODRIVER=wayland
export MOZ_ENABLE_WAYLAND=1

# copy wayfire.ini to $HOME/.config/ if not already there
configdir="${XDG_CONFIG_HOME:=${HOME}/.config}"
if [[ ! -f ${configdir}/wayfire.ini ]]; then
	cp /usr/share/wayfire/wayfire.ini "${configdir}"
fi

# Set sway keymap to match system-wide keymap only in absence of
# a user-created 'lock' file, just in case user doesn't want any
# modification of the config file.
if [ ! -e "${configdir}/lock" ]; then
    WF_KEYMAP=$(awk -F '=' -v q1=\' -v q2=\" '$1 == "KEYMAP" {gsub ("[" q1 q2 "]", "", $2); print $2}' /etc/vconsole.conf)
    export WF_KEYMAP
    sed -i \
        -e "s|xkb_layout = .*|xkb_layout = "${WF_KEYMAP}"|g" \
        "${configdir}/wayfire.ini"
fi

# override or add environment variables
[[ -f /etc/sysconfig/wayfire ]] && . /etc/sysconfig/wayfire

exec dbus-run-session -- /usr/bin/wayfire "$@"
