#!/bin/sh
#(c) Copyright Barry Kauler 2003,2004,2005,2006,2007 www.puppylinux.com
#2007 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)
# called by /root/.profile
# moved sync code for console/xorg kbd layout from xwin to /usr/sbin/input-wizard.
#
# $DISTRO_XORG_AUTO         : see /etc/DISTRO_SPECS.
# /var/local/xwin_no_xorg_auto_flag:
#   the presence of this file triggers xorg wizard (cli)
#   if /etc/X11/xorg.conf does not exist
#
# /var/local/xwin_disable_xerrs_log_flag
#   create this file to silence xerrs.log
#   some buggy / incompatible apps flood xerrs.log mercilessly


[ -z $DISPLAY ] || exit

export TEXTDOMAIN=xwin
export OUTPUT_CHARSET=UTF-8

if ! command -v Xorg >/dev/null 2>&1 ; then
	exit
fi

if [ -f /var/local/xwin_disable_xerrs_log_flag ] ; then
	LOGFILE_X='/dev/null'
else
	LOGFILE_X='/tmp/xerrs.log'
fi

if [ `id -u` -eq 0 -a ! -e /usr/bin/X ] ; then
	ln -snf Xorg /usr/bin/X
fi

if [ "$1" = "-default" ] ; then
	xorgwizard-automatic
	shift
fi

# Ensure current directory is root, in case changed at command prompt,
# so rox icon and menu item open only at home directory. rerwin
cd ~/

. /etc/rc.d/PUPSTATE # variables created at bootup by init script in initrd...
. /etc/DISTRO_SPECS # PUPMODE=current operating configuration,
. /etc/rc.d/BOOTCONSTRAINED

reset_monitor_settings() {

rm -f /var/lib/gdm/.config/monitors.xml 2>/dev/null

for lxpath2 in /etc/xdg /root/.config
do 
 if [ -e $lxpath2/autostart/lxrandr-autostart.desktop ]; then
  rm -f $lxpath2/autostart/lxrandr-autostart.desktop 2>/dev/null
 fi
done

for xfcepath in /etc/xdg/xfce4 /etc/xdg/xfce /root/.config/xfce4 /root/.config/xfce
do

 if [ -e $xfcepath/xfconf/xfce-perchannel-xml/displays.xml ]; then
echo '<?xml version="1.0" encoding="UTF-8"?>

<channel name="displays" version="1.0">
  <property name="Notify" type="bool" value="true"/>
</channel>' > $xfcepath/xfconf/xfce-perchannel-xml/displays.xml
 fi

done

rm -f /root/.screenlayout/* 2>/dev/null
rm -f /root/.config/monitors.xml 2>/dev/null
rm -f /root/.kde/share/apps/kscreen/* 2>/dev/null
rm -f /root/.kde/local/share/apps/kscreen/* 2>/dev/null
rm -f /root/.kde/share/config/krandrc 2>/dev/null
rm -f /root/.kde4/share/apps/kscreen/* 2>/dev/null
rm -f /root/.kde4/local/share/apps/kscreen/* 2>/dev/null
rm -f /root/.kde4/share/config/krandrc 2>/dev/null
rm -f /root/.local/share/kscreen/* 2>/dev/null
rm -f /root/.zarfy/* 2>/dev/null

if [ -d /home ]; then

 for lxf in $(find /home -name "lxrandr-autostart.desktop" -type f | grep "/.config/autostart/")	
 do
  if [ "$lxf" != "" ]; then
	rm -f $lxf 
  fi
 done
 
 for usr1 in $(ls -1 /home 2>/dev/null | tr '\n' ' ')
 do

	if [ -f /home/$usr1/.config/xfce4/xfconf/xfce-perchannel-xml/displays.xml ]; then
	echo '<?xml version="1.0" encoding="UTF-8"?>

	<channel name="displays" version="1.0">
	  <property name="Notify" type="bool" value="true"/>
	</channel>' > /home/$usr1/.config/xfce4/xfconf/xfce-perchannel-xml/displays.xml
	fi

	if [ -f /home/$usr1/.config/xfce/xfconf/xfce-perchannel-xml/displays.xml ]; then
	echo '<?xml version="1.0" encoding="UTF-8"?>

	<channel name="displays" version="1.0">
	  <property name="Notify" type="bool" value="true"/>
	</channel>' > /home/$usr1/.config/xfce/xfconf/xfce-perchannel-xml/displays.xml
	fi

	  rm -f /home/$usr1/.screenlayout/* 2>/dev/null
	  rm -f /home/$usr1/.config/monitors.xml 2>/dev/null
	  rm -f /home/$usr1/.kde/share/apps/kscreen/* 2>/dev/null
	  rm -f /home/$usr1/.kde/local/share/apps/kscreen/* 2>/dev/null
	  rm -f /home/$usr1/.kde/share/config/krandrc 2>/dev/null
	  rm -f /home/$usr1/.kde4/share/apps/kscreen/* 2>/dev/null
	  rm -f /home/$usr1/.kde4/local/share/apps/kscreen/* 2>/dev/null
	  rm -f /home/$usr1/.kde4/share/config/krandrc 2>/dev/null
	  rm -f /home/$usr1/.local/share/kscreen/* 2>/dev/null
	  rm -f /home/$usr1/.zarfy/* 2>/dev/null
	  
 done
 
fi
		
}

get_edid_hash() {

for medid in $(ls -1 /sys/class/drm/*/edid 2>/dev/null | grep "card" | grep "-")
do
 sc1="$(dirname $medid)/status"
 if [ "$(cat $sc1)" == "connected" ]; then
  md5sum $medid
 fi
done
		
}

config_video() {
	
if [ ! -d /var/hwdata ]; then
 mkdir -p /var/hwdata
fi

if [ ! -f /var/hwdata/screen.lst ]; then
 xConfig=1
elif [ ! -f /var/hwdata/videocards.lst ]; then
 xConfig=1
else
 xConfig=0
fi	

if [ $xConfig -eq 0 ]; then

    vlist="$(busybox lspci | grep "Class 03" | cut -c 21-29 | sort)"
    ocard="$(cat /var/hwdata/videocards.lst 2>/dev/null)"
    
    #Check if video card change
    if [ "$vlist" != "$ocard" ]; then
      #Video card change. Remember videocard
      echo "$vlist" > /var/hwdata/videocards.lst
      xConfig=1
    else
     xScreens="$(get_edid_hash)"
     oScreens="$(cat /var/hwdata/screen.lst 2>/dev/null)"
      #Check if screen doesn't change
       if [ "$xScreens" != "$oScreens" ]; then
         #Screen setup changed. Remember screen setup
         echo "$xScreens" > /var/hwdata/screen.lst
	 xConfig=1
       fi
    fi
    
fi

if [ $xConfig -ne 0 ]; then
  xorgwizard-automatic 
  reset_monitor_settings
  busybox lspci | grep "Class 03" | cut -c 21-29 | sort > /var/hwdata/videocards.lst
  get_edid_hash > /var/hwdata/screen.lst
fi
	
}



# automatic network reconnect. refer /usr/sbin/hostname-set
if [ -f /tmp/services/network_default_reconnect_required_flag ];then
	rm -f /tmp/services/network_default_reconnect_required_flag
	IFCONFIG="`ifconfig | grep '^[pwe]' | grep -v 'wmaster'`" #precaution.
	[ "$IFCONFIG" = "" ] && network_default_connect #/usr/sbin
fi

# enables to start a specific w.m. from commandline...
# this can also be an app that stars a desktop environment..
if [ "$1" ] ; then

 DEXEC="$1"

 case $DEXEC in
 lxde)
  if [ "$(which startlxde)" != "" ]; then
   DEXEC="startlxde"
  else
   DEXEC="lxde-session"
  fi
 ;;
 xfce|xfce4|gnome|lxqt|razor|mate|cinnamon)
  DEXEC="$DEXEC-session"
 ;;
 kde|tde|fluxbox) 
  DEXEC="start$DEXEC"
 ;;
 enlightenment) 
  DEXEC="enlightenment_start"
 ;;
 windowmaker) 
  DEXEC="wmaker"
 ;;
esac

if [ ! "`which $DEXEC 2>/dev/null`" ] && [ ! -x $DEXEC ] ; then
	echo "* $DEXEC does not exist or is not a valid executable.."
	exit 1
fi

 echo -n "$DEXEC" > /etc/windowmanager # /root/.xinitrc uses this file.

fi

# in some very strange situations this file might be empty
[ ! -s /etc/X11/xorg.conf ] && rm -f /etc/X11/xorg.conf

# Puppy Xorg Video Wizard...
# boot param pfix=xorgwizard
if [ -f /tmp/xwin_xorgwizard_cli ] ; then
	rm -f /tmp/xwin_xorgwizard_cli
	xorgwizard-cli
	xorgwizard-automatic
# normal operation
elif [ -f /etc/X11/xorg.conf ];then
	USING_DRIVER=$(grep '#card0driver' /etc/X11/xorg.conf | grep -v '#.*Driver')
	DRVRSPATH='/usr/lib/xorg/modules/drivers'
	if [ -d /usr/lib64/xorg/modules/drivers ] ; then
		DRVRSPATH='/usr/lib64/xorg/modules/drivers'
	fi
	if [ "$USING_DRIVER" -a -d "$DRVRSPATH" ] ; then #find location of video chip drivers...
		CURRENT_DRIVER="`grep '#card0driver' /etc/X11/xorg.conf | cut -f 2 -d '"'`"
		if [ "$CURRENT_DRIVER" ];then
			if ! [ "`find -L $DRVRSPATH -type f -name "*${CURRENT_DRIVER}*"`" ] ; then
				#driver file not found, comment out
				sed -i "s|.*#card0driver|#	Driver      \"${CURRENT_DRIVER}\" #card0driver|" /etc/X11/xorg.conf
			fi
		fi
	fi
else
	#* /etc/X11/xorg.conf does not exist *
	rm -f /root/.XLOADED 2> /dev/null #not necessary, precaution.
fi

if [ "$(uname -m | grep -E "[i|x]*86")" != "" ] || [ "$(uname -m)" == "x86_64" ]; then
 config_video
fi

# J_Reys idea (see note further down)...
if [ -f /root/.XLOADED ];then
	if [ "`cat /root/.XLOADED`" = "true" ];then
		#last time X ran, PC hung and had to be rebooted...
		dialog --timeout 30 --title "$(gettext 'Warning')" --yes-label "$(gettext 'Ignore')" --no-label "$(gettext 'Commandline')" --yesno "$(gettext 'X seems to have exited uncleanly the last time you ran Puppy.  This is usually because of an improper shutdown (such as a power failure), but may be because something is broken.')

$(gettext 'If it was just something like a power failure, wait for 30 seconds or choose <Ignore> for normal startup of X...')

$(gettext 'If there is a problem, such as X not working, choose <Commandline> to drop out to a commandline. There will then be further advice how to fix X...')

$(gettext 'If undecided, wait 30 seconds for normal startup of X...')" 0 0
		if [ ! $? = 1 ]; then
			rm /root/.XLOADED
		else
			echo -en "\\033[1;31m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
			echo '
'$(gettext 'It seems that last time X ran, the computer hung and you had to reboot.')'
'$(gettext 'Have now dropped down to the commandline. If you want to run the Xorg')'
'$(gettext 'Video Wizard, type "xorgwizard", and after configuring /etc/X11/xorg.conf')'
'$(gettext '(hopefully correctly this time!) type "xwin" to start X.')''
			echo -e "\\033[0;39m"
			rm -f /root/.XLOADED #otherwise cannot start X.
			exit
		fi
	fi
fi

if type pcmanfm >/dev/null 2>&1 ; then
	rm -f $HOME/.cache/menu-cached* $HOME/.cache/pcmanfm* $HOME/.cache/menus/*
fi

for i in /tmp/runtime-* ; do
	[ -d ${i} ] || continue
	find ${i} -not -type d -delete
done
if [ "$XDG_RUNTIME_DIR" ] && [ -d "$XDG_RUNTIME_DIR" ] ; then
	find "$XDG_RUNTIME_DIR" -not -type d -delete
fi

killall -9 pup_event_frontend_d 2>/dev/null

#-- finally, start X... --
# J_Rey had a good idea, flag XLOADED... and set to false on exit.
# but if PC hangs, XLOADED will still be true, so will know it is broken.
if [ -f $HOME/.xinitrc ] ; then
	XINITRC="$HOME/.xinitrc"
elif [ -f /root/.xinitrc ] ; then
	XINITRC="/root/.xinitrc"
fi
echo -n "true" > /root/.XLOADED
echo "$(gettext 'Starting X, specs in /etc/X11/xorg.conf'). ${XINITRC}...."
#-----------------------------------------------------------------------
if [ "$LOGFILE_X" = "/dev/null" ] ; then
	echo 'logging of X errors is disabled' > /tmp/xerrs.log
	echo 'remove /var/local/xwin_disable_xerrs_log_flag to enable it, then restart X' >> /tmp/xerrs.log
fi
if [ -f /var/local/xwin_run_as_spot_flag ] ; then
	(
		if [ ! -L /var/log/Xorg.0.log ] ; then
			rm -f /var/log/Xorg.0.log
			ln -s /home/spot/.local/share/xorg/Xorg.0.log /var/log/
		fi

		export DISPLAY=":0"

		(
			while ! xdpyinfo > /dev/null 2>&1; do
				sleep 0.1
			done

			exec ${XINITRC}
		) &
		PID=$!

		run-as-spot X -br -nolisten tcp || (rm -f /var/log/Xorg.0.log && X -br -nolisten tcp && rm -f /var/local/xwin_run_as_spot_flag)
		kill $PID 2>/dev/null
		unset DISPLAY
	) > $LOGFILE_X 2>&1
else
	/usr/bin/xinit ${XINITRC} -- -br -nolisten tcp > $LOGFILE_X 2>&1
fi
#-----------------------------------------------------------------------
echo -n "false" > /root/.XLOADED #see note above.
rm -f /tmp/services/x_display

sleep 0.5
# ...if PC hung, run xorgwizard at next bootup (see further up).

load_consolefont # load console font on exit from X.
# console font is loaded in quicksetup if locale changed.
echo '--------'
echo ''$(gettext 'Exited from X. Type "xwin [jwm]" to restart X ([ ] mean optional).')''
echo ''$(gettext 'Type "xwin -default [jwm]" to restart X with the default xorg.conf')''
echo '-'
echo ''$(gettext '(To shutdown PC type "poweroff", to reboot PC type "reboot")')''
echo ''$(gettext 'If X failed to start, type "xorgwizard" to setup X')''

[ -f /tmp/wmexitmode.txt ] || exit

# Shutdown menu calls wmreboot, wmpoweroff, wmexit or restartwm, which create this file...
WMEXITMODE="`cat /tmp/wmexitmode.txt`"

if [ "$WMEXITMODE" = "exit" ];then #see /usr/bin/wmexit.
	rm -f /tmp/wmexitmode.txt
	exit
fi

[ "$WMEXITMODE" = "poweroff" ] && exec poweroff #see /usr/bin/wmpoweroff
[ "$WMEXITMODE" = "reboot" ] && exec reboot #see /usr/bin/wmreboot
[ "$WMEXITMODE" = "shutdown" ] && exec shutdown

# restart window manager...
# make a gross assumption, if wmexitmode.txt exists, haven't already exited this script, then want
# to restart maybe with different window manager. /etc/windowmanager already has desired w.m.
rm -f /tmp/wmexitmode.txt #definitely delete it now.

# thanks GuestToo for advice on this, works with chooselocale script...
NEWLANG="`cat /etc/profile | grep '^LANG=' | cut -f 2 -d '='`"
if [ "$NEWLANG" -a "$NEWLANG" != "$LANG" ];then #precaution
	export LANG=$NEWLANG
fi

# hostname-set changed HOSTNAME, via quicksetup, X is restarted,
# update $HOSTNAME (was exported at bootup in /etc/profile)...
NEWHOSTNAME="`cat /etc/hostname | tr -d '\n'`"

if [ "$NEWHOSTNAME" -a "$NEWHOSTNAME" != "$HOSTNAME" ];then
	export HOSTNAME=$NEWHOSTNAME
fi

exec xwin

### END ###