#!/bin/bash
# Switch to/from SpaceFM and JWM desktop managers

export TEXTDOMAIN=spacefm2jwm
export OUTPUT_CHARSET=UTF-8

[ -f $HOME/.config/autostart/spacefm.desktop ] && DTOP=SpaceFM || DTOP=JWM

[ -f /usr/local/lib/X11/pixmaps/info.xpm ] && ICON="/usr/local/lib/X11/pixmaps/question.xpm" || ICON=""

pidof conky && CONKY_ACTIVE=yes

conkyrefresh(){
  [ -n "$(pidof conky 2>/dev/null)" ] && killall conky &
  sleep 5
  conky -c "$HOME/.config/conky-gtk/conkyrc" 2>/dev/null &
}
export -f conkyrefresh

if [ "$DTOP" = "SpaceFM" ]; then # switch to JWM
  Xdialog --stdout --title "$(gettext 'Desktop Switcher')" \
  --backtitle "$(gettext 'Current Desktop'): $DTOP" \
  --icon "$ICON" \
  --screen-center \
  --buttons-style text \
  --cancel-label "$(gettext 'Cancel')" \
  --ok-label "$(gettext 'Switch')" \
  --yesno "$(gettext 'Switch to JWM desktop ?')" 7 42

  case $? in
    0)
        gtkdialog-splash -close never -timeout 2 -margin 10 -placement center -fontsize large -bg goldenrod -text " $(gettext 'Switching to JWM desktop !')"
        rm -f /usr/share/applications/desktop-settings.desktop
        rm -f $HOME/.config/autostart/spacefm.desktop
        wallp=$(cat "$HOME/.config/wallpaper/bg_img")
        set_bg $wallp
        [ "$CONKY_ACTIVE" = "yes" ] && conkyrefresh &
        spacefmPID=$(pgrep -f 'spacefm') # PID of 'spacefm --desktop' daemon is not sufficient, must kill all SpaceFM PIDs
        [ -n "$spacefmPID" ] && kill -9 $spacefmPID
        ;;
    1)
        exit
        ;;
    255)
        exit
        ;;
  esac
else # switch to SpaceFM
  Xdialog --stdout --title "$(gettext 'Desktop Switcher')" \
  --backtitle "$(gettext 'Current Desktop'): $DTOP" \
  --icon "$ICON" \
  --screen-center \
  --buttons-style text \
  --cancel-label "$(gettext 'Cancel')" \
  --ok-label "$(gettext 'Switch')" \
  --yesno "$(gettext 'Switch to SpaceFM desktop ?')" 7 42

  case $? in
    0)
        gtkdialog-splash -close never -timeout 2 -margin 10 -placement center -fontsize large -bg goldenrod -text " $(gettext 'Switching to SpaceFM desktop !')" 
        echo '[Desktop Entry]
Version=1.0
Encoding=UTF-8
Type=Application
Name=Desktop settings
Exec=spacefm --show-pref=3
Icon=/usr/share/icons/hicolor/48x48/apps/spacefm-48-pyramid-blue.png
Terminal=false
GenericName=SpaceFM desktop preferences
Categories=X-Desktop;
Comment=Desktop preferences' > /usr/share/applications/desktop-settings.desktop
        echo '[Desktop Entry]
Name=SpaceFM
Exec=spacefm --desktop
Encoding=UTF-8
Type=Application
Icon=/usr/share/icons/hicolor/48x48/apps/spacefm.png' > $HOME/.config/autostart/spacefm.desktop
        [ "$CONKY_ACTIVE" = "yes" ] && conkyrefresh &
        spacefm --desktop &
        ;;
    1)
        exit
        ;;
    255)
        exit
        ;;
  esac
fi

exit 0
