#!/bin/sh
#(c) Copyright Barry Kauler 2003,2004,2005,2006,2007,2013 www.puppylinux.com
#2007 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)
#131204 have taken script from woof, 130725, cut down for quirky6.
#140217 if need to do hard reboot, make sure /root/.XLOADED written to disk.
#150102 now want File Open dialogs to default to /file.
#160914 no longer using mouse and keyboard xorg drivers, now evdev, see /etc/X11/xorg.conf.d/10-evdev-puppy.conf
#161106 remove keyboard layout code.
#170203 easy linux, new home. 170809 change "Puppy" to "Easy" in msg.
#180317 backup xorg.conf.d when video hardware change (see also xorgwizard-cli).
#180321 wait for kernel video drivers to load. 180410 revert. 180501 restored.
#190829 /home is now a symlink to /mnt/${WKG_DEV}/${WKG_DIR}home (see rc.sysinit)
#200113 add PuppyHardwareProfile for 'xorg.conf.d' folder (extension of 180317).
#200114 improve PuppyHardwareProfile. see also: /usr/sbin/xorgwizard, xorgwizard-cli, xorgwizard-automatic. 201020
#200209 need a hack for some intel gpu's.
#200516 restore support for quirky.

export TEXTDOMAIN=xwin
export OUTPUT_CHARSET=UTF-8
. gettext.sh

export LANGORG=$LANG
HOSTNAMEORIG=$HOSTNAME #120511

[ -z $DISPLAY ] || exit #v2.11 from GuestToo.

. /etc/rc.d/PUPSTATE #has WKG_DEV, WKG_DIR
. /etc/DISTRO_SPECS

#cd ~   #v3.98 Ensure current directory is root, in case changed at command prompt, so rox icon and menu item open only at home directory. rerwin
#150102 now want File Open dialogs to default to /file. 170203 easy linux, new home...
#cd /mnt/${WKG_DEV}/${WKG_DIR}home
#190829 /home is now a symlink to /mnt/${WKG_DEV}/${WKG_DIR}home (see rc.sysinit)
if [ -d /file ];then #200516 support quirky.
 cd /file
else
 cd /home
fi

KERNELVER="`uname -r`" #w479

#180501 restored this, removed "udevadm settle" in rc.sysinit...
##180410 remove (inserted "udevadm settle" in rc.sysinit instead)...
##180321
echo -n 'Waiting for kernel video drivers to load: '
CNT=0
BLKi="$(grep -o -w "intel" /etc/modprobe.d/blacklist.conf)"
BLKn="$(grep -o -w "nouveau" /etc/modprobe.d/blacklist.conf)"
BLKa="$(grep -o -w -E "radeon|amdgpu" /etc/modprobe.d/blacklist.conf)"
while [ $CNT -lt 20 ];do
 FLG=0
 for aVID in `busybox lspci -m -k | grep '"Class 0300"' | cut -f 4,12 -d '"' | tr '\n' ' '`
 do
  case "$aVID" in #ex: aVID=8086"i915
   "8086") [ "$BLKi" ] && continue ;;
   "10de") [ "$BLKn" ] && continue ;;
   "1002") [ "$BLKa" ] && continue ;;
   "1022") [ "$BLKa" ] && continue ;;
   *\"*) echo -n "${aVID/*\"/} "; continue ;;
  esac
  #fall to here, then video driver not yet loaded.
  FLG=1
 done
 [ $FLG -eq 0 ] && break
 sleep 0.5
 CNT=$(($CNT+1))
 echo -n "${CNT} "
done
echo

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

#0.9.9 enables to start a specific w.m. from commandline...
[ $1 ] && echo -n "$1" > /etc/windowmanager #note, /root/.xinitrc uses this file.

#update 10-evdev-puppy.conf if mouse has changed...
MOUSEDEV="`cat /etc/mousedevice`" #autodetected in rc.sysinit
OLDMOUSEDEV="`cat /etc/oldmousedevice 2>/dev/null`" #set in rc.sysinit. 130725
if [ ! "$OLDMOUSEDEV" = "$MOUSEDEV" ];then
 if [ ! "$OLDMOUSEDEV" = "nothing" ];then #"nothing" on first boot.
  if [ -f /etc/X11/xorg.conf.d/10-evdev-puppy.conf ];then
   case `cat /etc/mousedevice | cut -c 1-4` in
    "inpu") #"input/mice", usb
     sed -i -e 's/\W\+Option\W\+"Protocol"\W\+"\(\(\w\+\/\w\+\)\|\(\w\+\)\)\W\+#mouse0protocol/	Option	    "Protocol" "IMPS\/2" #mouse0protocol/g' /etc/X11/xorg.conf.d/10-evdev-puppy.conf
    ;;
    "ttyS") #ttyS0,1,2,3, serial
     sed -i -e 's/\W\+Option\W\+"Protocol"\W\+"\(\(\w\+\/\w\+\)\|\(\w\+\)\)\W\+#mouse0protocol/	Option	    "Protocol" "Microsoft" #mouse0protocol/g' /etc/X11/xorg.conf.d/10-evdev-puppy.conf
    ;;
    *)
     sed -i -e 's/\W\+Option\W\+"Protocol"\W\+"\(\(\w\+\/\w\+\)\|\(\w\+\)\)\W\+#mouse0protocol/	Option	    "Protocol" "auto" #mouse0protocol/g' /etc/X11/xorg.conf.d/10-evdev-puppy.conf
    ;;
   esac
  fi
 fi
 OLDMOUSEDEV="$MOUSEDEV" #v411 old is now current mouse
 echo -n "$OLDMOUSEDEV" > /etc/oldmousedevice #v411
fi

#v408 k2.6.25.16 has serial driver as a module... 110721 o/p to null...
[ "`grep 'ttyS' /etc/mousedevice`" != "" ] && modprobe sermouse > /dev/null 2>&1

#video hardware profile...
if [ -f /etc/X11/xorg.conf ];then
   
 #200114 improve video hardware profile...
 GPU_IDS=''; EDIDsum=''
 if which lspci >/dev/null;then #arm boards usually don't have pci bus.
  GPU_IDS="$(lspci -d ::0300 -n | cut -f 3 -d ' ' | tr '\n' '_')" #ex: 8086:0102_ note: maybe more than one card.
 fi
 if [ -d /sys/class/drm ];then
  for aCARD in /sys/class/drm/card*
  do
   if grep '^connected' ${aCARD}/status >/dev/null 2>&1;then
    CARDname="${aCARD##*/}" #ex: card0-HDMI-A-2
    if [ -e ${aCARD}/edid ];then
     EDIDsum="$(xxd -p -c30 ${aCARD}/edid | cksum - | cut -f 1 -d ' ')"
     break
    fi
   fi
  done
 fi
 HARDWAREPROFILE="${GPU_IDS}+${EDIDsum}"
   
 #find out if current xorg.conf matches this profile...
 CURRENTPROFILE="$(cat /etc/X11/xorg.conf | grep '^#PuppyHardwareProfile' | cut -f 2 -d '=' | cut -f 2 -d "'" | cut -f 1 -d ' ')" #200120
 if [ ! "$CURRENTPROFILE" = "$HARDWAREPROFILE" ];then
  #video hardware has changed. either changed monitor or booting different PC.
  #same current xorg.conf as a profiled filename...
  mv -f /etc/X11/xorg.conf /etc/X11/xorg.conf.${CURRENTPROFILE}
  #180317 backup xorg.conf.d also... 200113...
  [ -d /etc/X11/xorg.conf.d.${CURRENTPROFILE} ] && rm -rf /etc/X11/xorg.conf.d.${CURRENTPROFILE}
  echo "PuppyHardwareProfile='${CURRENTPROFILE}'" > /etc/X11/xorg.conf.d/PuppyHardwareProfile #200113
  cp -a /etc/X11/xorg.conf.d /etc/X11/xorg.conf.d.${CURRENTPROFILE}
  #if a previous profiled filename for new hardware, use that...
  [ -f /etc/X11/xorg.conf.${HARDWAREPROFILE} ] && cp -af /etc/X11/xorg.conf.${HARDWAREPROFILE} /etc/X11/xorg.conf
  #180317 xorg.conf.d may be backed up with hardware profile...
  if [ -d /etc/X11/xorg.conf.d.${HARDWAREPROFILE} ];then
   rm -rf /etc/X11/xorg.conf.d
   cp -a /etc/X11/xorg.conf.d.${HARDWAREPROFILE} /etc/X11/xorg.conf.d
  fi
 fi
fi
 
if [ ! -f /etc/X11/xorg.conf ];then
 rm -f /root/.XLOADED 2> /dev/null #not necessary, precaution.
 if [ "$DISTRO_XORG_AUTO" = "yes" ];then #see /etc/DISTRO_SPECS.
  /usr/sbin/xorgwizard-automatic
 else
  /usr/sbin/xorgwizard-cli
 fi
fi

#200209 need a hack for some intel gpu's...
#have renamed 20-intel-* files to 20-gpu-intel*, so delete the old ones (existing installation)...
rm -f /etc/X11/xorg.conf.d/20-intel-* 2>/dev/null
rm -f /etc/X11/xorg.conf.d/intel-gpu*.conf 2>/dev/null
. /etc/X11/xorg.conf.d/PuppyHardwareProfile #has variable PuppyHardwareProfile
[ "$PuppyHardwareProfile" ] && HARDWAREPROFILE="${PuppyHardwareProfile}"
#i was doing this in rc.hacks, called from rc.sysinit, but now do here...
#if xorgwizard-cli or xorgwizard-automatic have not created a /etc/X11/xorg.conf.d/20-gpu-*.conf
#(or it was created manually), apply any required hack here (ex: force uxa accel for intel)...
ls -1 /etc/X11/xorg.conf.d/20-gpu-*.conf >/dev/null 2>&1
if [ $? -ne 0 ];then
 #no pre-existing 20-gpu-*.conf, so apply hack script...
 HARDWAREPROFILE="${HARDWAREPROFILE}" /usr/sbin/xorg-gpu-hacks
fi

#v1.0.7 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 Easy.  This is usually because of an improper shutdown (such as a power failure), but may be because something is broken (such as hanging, and holding down the power-button to force a shutdown).')

$(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 'and the .conf files in /etc/X11/xorg.conf.d/')'
'$(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

MOUSEBUTTONS=3
[ -e /etc/mousebuttons ] && MOUSEBUTTONS=`cat /etc/mousebuttons`

#v424 bad hack, i somehow get /dev/mouse pointing to psaux when chose a serial mouse, don't know why...
[ "`grep 'ttyS' /etc/mousedevice`" != "" ] && ln -snf $MOUSEDEV /dev/mouse

#161106 why need this? quicksetup does this. comment out...
##100520 attempt fix keyboard layout not getting updated...
#[ ! -f /etc/keymap ] && echo -n "us" > /etc/keymap #maybe lupu needs this.
#[ ! -f /etc/keymap_previous ] && echo -n "us" > /etc/keymap_previous
#KEYMAPNOW="`cat /etc/keymap`"
#KEYMAPPREV="`cat /etc/keymap_previous`"
#if [ "$KEYMAPNOW" != "$KEYMAPPREV" ];then
# cp -f /etc/keymap /etc/keymap_previous
# #100520 bring this code back again...
# #100215 moved this code to /usr/sbin/input-wizard, avoid automatic overwriting of any user edit of xorg.conf...
# #100127 make sure xorg keyboard layout matches console setting (same code in xorgwizard)...
## if [ "$HAVEX" = "Xorg" ];then
#  xCONSKEYMAP="`cat /etc/keymap | cut -c 1-2`"
#  [ "$xCONSKEYMAP" = "" ] && xCONSKEYMAP="us"
#  case $xCONSKEYMAP in
#   az) XKEYMAP="fr" ;;     #azerty
#   wa) XKEYMAP="fr" ;;     #wangbe
#   dv) XKEYMAP="dvorak" ;; #dvorak
#   cr) XKEYMAP="cz" ;;     #croat
#   sl) XKEYMAP="si" ;;     #slovene v2.12 bugfix, changed from 'sk' to 'si' (sk is slovakia)
#   sv) XKEYMAP="se" ;;     #sweden
#   uk) XKEYMAP="gb" ;;     #united kingdom
#   *)  XKEYMAP="$xCONSKEYMAP" ;;
#  esac
#  #160914 different layout in recent xorg (and no longer using /etc/X11/xkb)...
#  if [ -d /usr/share/X11/xkb/symbols ];then #100127 fallback... 
#   if [ ! -f /usr/share/X11/xkb/symbols/pc/${XKEYMAP} ];then #160914 'pc' no longer present.
#    if [ ! -f /usr/share/X11/xkb/symbols/${XKEYMAP} ];then
#     echo "$(gettext 'ERROR: Console keyboard') `cat /etc/keymap` $(gettext 'no matching Xorg layout. PLEASE REPORT TO BK')"
#     XKEYMAP='us'
#    fi
#   fi
#  fi
#  currXKEYMAP="`grep '#xkeymap0' /etc/X11/xorg.conf.d/10-evdev-puppy.conf | tr '\t' ' ' | tr -s ' ' | cut -f 4 -d '"'`" #'geany fix
#  if [ "$currXKEYMAP" != "$XKEYMAP" ];then
#   skPATTERN="s%.*#xkeymap0%	Option      \"XkbLayout\" \"${XKEYMAP}\" #xkeymap0%"
#   sed -i -e "${skPATTERN}" /etc/X11/xorg.conf.d/10-evdev-puppy.conf
#  fi
#fi

#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.
echo -n "true" > /root/.XLOADED
#chmod 666 /root/.XLOADED #130609 precaution, if change to user 'fido' at X shutdown, need to be able to delete this at next boot.
fsync /root/.XLOADED #140217 if need to do hard reboot, make sure /root/.XLOADED written to disk.

echo "$(gettext 'Starting X, specs in /etc/X11, startup apps /root/.xinitrc...')"
#v2.11 G2 suggested -br for black background instead of checked...
/usr/bin/xinit /root/.xinitrc -- -br -nolisten tcp -nolisten local > /tmp/xerrs.log 2>&1

echo -n "false" > /root/.XLOADED #see note above.
#...if PC hung, run xorgwizard at next bootup (see further up).

load_consolefont #120301 seems have to do this on exit from X. (new script)

#unicode_start #i18n rodin.s for unicode start after exit from X. ??????what is this??????
#120224 ...console font is loaded in quicksetup if locale changed.
echo ''$(gettext 'Exited from X. Type "xwin [fvwm95|jwm]" to restart X ([ ] mean optional).')''
echo ''$(gettext '(To shutdown PC type "poweroff", to reboot PC type "reboot")')''
echo -en "\\033[1;35m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
echo -n ''$(gettext 'If X failed to start, type "xorgwizard" to setup X')''
echo -e "\\033[0;39m"

#Shutdown menu calls wmreboot, wmpoweroff, wmexit or restartwm, which create this file...
if [ -f /tmp/wmexitmode.txt ];then
 WMEXITMODE="`cat /tmp/wmexitmode.txt`"
 if [ "$WMEXITMODE" = "exit" ];then #see /usr/bin/wmexit.
  rm -f /tmp/wmexitmode.txt #w478
  exit
 fi
 #rm -f /tmp/wmexitmode.txt ...no, removed in rc.shutdown.
 [ "$WMEXITMODE" = "poweroff" ] && exec /sbin/poweroff #see /usr/bin/wmpoweroff
 [ "$WMEXITMODE" = "reboot" ] && exec /sbin/reboot #see /usr/bin/wmreboot
 #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.
 #v1.0.5 thanks GuestToo for advice on this, works with chooselocale script...
 NEWLANG="`cat /etc/profile | grep '^LANG=' | cut -f 2 -d '='`"
 if [ "$NEWLANG" ];then #precaution
  if [ "$NEWLANG" != "$LANG" ];then
   export LANG=$NEWLANG
  fi
 fi
 #120511 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" ];then #over-the-top paranoid precaution.
  if [ "$NEWHOSTNAME" != "$HOSTNAME" ];then
   export HOSTNAME=$NEWHOSTNAME
  fi
 fi
 exec xwin
fi

#the end#
