#!/bin/sh
# Moodtop OS graphical session (started by greetd). `mood-session --logout` ends it.
if [ "$1" = "--logout" ]; then
  pkill -u "$(id -u)" -x wayfire; pkill -u "$(id -u)" -x labwc; exit 0
fi
export XDG_CURRENT_DESKTOP=Mood:wlroots
export XDG_SESSION_DESKTOP=moodtop
export XDG_SESSION_TYPE=wayland
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM="wayland;xcb"
export SDL_VIDEODRIVER="wayland,x11"
export GDK_BACKEND=wayland,x11
export ELECTRON_OZONE_PLATFORM_HINT=auto
export _JAVA_AWT_WM_NONREPARENTING=1
# school proxy (Settings → School network): GTK/WebKit read it from GSettings, terminal tools from env
export GIO_USE_PROXY_RESOLVER=gnome
[ -f "$HOME/.config/environment.d/90-mood-proxy.conf" ] && { set -a; . "$HOME/.config/environment.d/90-mood-proxy.conf"; set +a; }
# Mood VPN (Psiphon): undo a proxy left pointing at a dead tunnel, reconnect if it was on at logout
(sleep 5; /usr/lib/mood/runtime/mood-vpn restore) >/dev/null 2>&1 &
[ -f /etc/profile.d/flatpak.sh ] && . /etc/profile.d/flatpak.sh
[ -f /etc/mood/session.env ] && . /etc/mood/session.env
xdg-user-dirs-update >/dev/null 2>&1
mkdir -p "$HOME/Documents" "$HOME/Pictures/Screenshots" "$HOME/Pictures/Wallpapers" "$HOME/Downloads" "$HOME/Music" "$HOME/Videos" "$HOME/Applications"
/usr/lib/mood/runtime/moodtop-wm 2>/dev/null
eval "$(python3 -c 'import json,os;s=json.load(open(os.path.expanduser("~/.config/mood/settings.json"))).get("cursor",{});print("export XCURSOR_THEME=%s XCURSOR_SIZE=%d"%(s.get("theme","Bibata-Modern-Classic"),int(s.get("size",24))))' 2>/dev/null || echo 'export XCURSOR_THEME=Bibata-Modern-Classic XCURSOR_SIZE=24')"
LOG="${XDG_RUNTIME_DIR:-/tmp}/moodtop-session.log"

safe_mode() {
  # No usable GPU (or `moodtop.safe` on the boot menu): labwc on the CPU renderer. Effects are off but everything works.
  export WLR_RENDERER=pixman WLR_NO_HARDWARE_CURSORS=1 WEBKIT_DISABLE_DMABUF_RENDERER=1 LIBGL_ALWAYS_SOFTWARE=1 MOODTOP_SAFE=1
  exec labwc -C /etc/xdg/labwc >>"$LOG" 2>&1
}
grep -qw moodtop.safe /proc/cmdline && safe_mode
start=$(date +%s)
wayfire -c "$HOME/.config/wayfire.ini" >"$LOG" 2>&1
rc=$?
# Wayfire died straight away (typically: no OpenGL ES) -> fall back instead of dumping the user at a login prompt.
if [ $rc -ne 0 ] && [ $(( $(date +%s) - start )) -lt 15 ]; then safe_mode; fi
exit $rc
