#!/bin/sh
#introduced v0.9.8
#called from /root/.fvwm95rc, .jwmrc at shutdown.
#110918 call new script 'shutdownconfig'.
#120216 offer to set default language in initrd.
#130221 return code 255 to abort shutdown.
#141206 fix if only have busybox ps.
#200229 "reboot to commandline" calls here with passed param "nox"

. /etc/rc.d/PUPSTATE

#200229
if [ "${1}" == "nox" ];then
 touch /root/bootcnt.txt #see /root/.profile at bootup.
 if [ $PUPMODE -eq 5 ];then
  if [ $DISPLAY ];then
   popup "process=wait terminate=ok background=#ff8080|<big>WARNING: A save-file is required to reboot to commandline</big>"
  fi
 fi
fi

if [ $DISPLAY ];then #paranoid precaution, check X still running

 #120216 offer to set default language in initrd...
 if [ -d /initrd ];then
  GIVEITAGO='yes'
  LANG1=${LANG%_*} #ex: en
  [ "$LANG1" = "en" ] && GIVEITAGO='no'
  if [ -f /var/local/lang2initrd.log ];then #read log from /usr/sbin/lang2initrd
   [ "`grep "^DECLINED ${DISTRO_IDSTRING}" /var/local/lang2initrd.log`" != "" ] && GIVEITAGO='no'
   [ "`grep "^SUCCESS ${DISTRO_IDSTRING}" /var/local/lang2initrd.log`" != "" ] && GIVEITAGO='no'
  fi
  [ "$GIVEITAGO" = "yes" ] && /usr/sbin/lang2initrd $LANG
 fi

 if [ $PUPMODE -eq 5 ];then #first shutdown.
  shutdownconfig #dlgs for creating save-file.
  #...writes results to /tmp/shutdownconfig_results, which /etc/rc.d/rc.shutdown reads.
  [ $? -eq 255 ] && exit #abort shutdown. 130221
 fi
fi

#/sbin/pup_event_frontend_d will quit if this file exists...
echo -n "reboot" > /tmp/wmexitmode.txt

#v403 give time for /sbin/pup_event_frontend_d to quit.
#w478 testing 2.6.18.1 kernel, pup_event_frontend_d did not exit when it
#detected /tmp/wmeximode.txt, but became 'defunct'...
KCNT=0
#PSPEFD="`ps -C pup_event_frontend_d | grep 'pup_event_front' | grep -v 'defunct'`"
#141206 may only have busybox ps, does not support -C ...
PSPEFD="`busybox ps | grep -v 'grep' | grep 'pup_event_front' | grep -v 'defunct'`"
#while [ "`pidof pup_event_frontend_d`" != "" ];do
while [ "$PSPEFD" != "" ];do
 sleep 0.5
 KCNT=`expr $KCNT + 1`
 [ $KCNT -gt 60 ] && break #30 secs.
 #PSPEFD="`ps -C pup_event_frontend_d | grep 'pup_event_front' | grep -v 'defunct'`"
 PSPEFD="`busybox ps | grep -v 'grep' | grep 'pup_event_front' | grep -v 'defunct'`" #141206
done
sleep 0.2

sync

#w003
if [ "`pidof xfce4-panel`" != "" ];then
 #killall xfce4-panel
 kill `pidof xfce4-panel`
 exit
fi

#w003
CURRENTWM="`cat /etc/windowmanager`"
kill -9 `pidof $CURRENTWM`

#killall X #default is SIGTERM.
#sleep 1           #v1.0.7
#exec killall -9 X #v1.0.7 make sure X is killed.

#after exit from X, there is a return to /usr/X11R7/bin/xwin,
#which reads /tmp/wmexitmode.
