#!/bin/bash

# output to syslog and stderr
# with PID and syslog identity 'sway'
exec 1> >(logger --id=$$ --stderr --tag sway) 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,x11
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 configuration files to ~/.config/sway if not already there
configdir="${XDG_CONFIG_HOME:=${HOME}/.config/sway}"

if [ ! -e "${configdir}" ]; then
    mkdir -p ${configdir}
fi

if [[ ! -f ${configdir}/config ]]; then
	cp /etc/sway/config "${configdir}/config"
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
    SWAY_KEYMAP=$(awk -F '=' -v q1=\' -v q2=\" '$1 == "KEYMAP" {gsub ("[" q1 q2 "]", "", $2); print $2}' /etc/vconsole.conf)
    export SWAY_KEYMAP
    sed -i \
        -e "s|xkb_layout .*|xkb_layout "\"${SWAY_KEYMAP}\""|g" \
        "${configdir}/config"
fi

# override or add environment variables
[[ -f /etc/sysconfig/sway ]] && source /etc/sysconfig/sway

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

