#!/bin/sh

COMPOSITOR="/usr/bin/phoc"
PHOC_INI="/usr/share/phosh/phoc.ini"
PHOSH_SESSION_BIN=${PHOSH_SESSION_BIN:-gnome-session}

help()
{
  cat <<EOF
phosh-session - Session start script for Phosh

This program is usually invoked by a display manager.

Usage: phosh-session
EOF
  exit 0
}


version()
{
   echo "0.59.0"
   exit 0
}

case "$1" in
  -h|-\?|--help)
    help
    ;;
  --version)
    version
    ;;
esac

if [ -x /usr/bin/phoc ]; then
  COMPOSITOR=/usr/bin/phoc
fi

if [ -f /etc/phosh/phoc.ini ]; then
  PHOC_INI=/etc/phosh/phoc.ini
fi

# Mode and scale picked in Settings, saved by phosh with a copy of the system phoc.ini. phoc
# starts with the system file as it is now plus mode and scale from that copy: a device update
# of the system file reaches it too. The copy as it is only if that fails.
USER_PHOC_INI="${XDG_CONFIG_HOME:-$HOME/.config}/phosh/phoc.ini"
MERGED_PHOC_INI="$XDG_RUNTIME_DIR/phoc.ini"
if [ -f "$USER_PHOC_INI" ]; then
  if [ -d "$XDG_RUNTIME_DIR" ] &&
     /usr/lib/phosh/plinius/phoc-ini-merge "$PHOC_INI" "$USER_PHOC_INI" > "$MERGED_PHOC_INI.new" &&
     mv -f "$MERGED_PHOC_INI.new" "$MERGED_PHOC_INI"; then
    PHOC_INI="$MERGED_PHOC_INI"
  else
    [ -d "$XDG_RUNTIME_DIR" ] && rm -f "$MERGED_PHOC_INI.new"
    PHOC_INI="$USER_PHOC_INI"
  fi
fi

if [ -f "$HOME/.phoshdebug" ]; then
  echo "WARN: .phoshdebug found."
  . "$HOME/.phoshdebug"
fi

if which systemd-cat >/dev/null 2>&1; then
  SYSTEMD_CAT="systemd-cat -t phoc"
fi

if [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
  echo "INFO: No DBus user session found, spawning it."
  DBUS_RUN_SESSION="dbus-run-session --"
fi

[ -n "$WLR_BACKENDS" ] || WLR_BACKENDS=drm,libinput
export WLR_BACKENDS
exec $SYSTEMD_CAT $DBUS_RUN_SESSION "${COMPOSITOR}" -v -S -C "${PHOC_INI}" -E "${PHOSH_SESSION_BIN} --session=phosh"
