#!/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.

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

KERNELVER="`uname -r`" #w479

#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

#Puppy Xorg Video Wizard...
 if [ -f /etc/X11/xorg.conf ];then
   if [ "`which ddcprobe`" = "" ];then  #120517
    #arm board, does not support ddcprobe (refer also /usr/sbin/xorgwizard-automatic)...
    HARDWAREPROFILE='armsystem'
   else
    #v2.13 video hardware profile (must be same as in xorgwizard)...
    DDCPROBE="`ddcprobe`"
    #v2.17 patch from Nightflyer... as in xwin, may have to run ddcprobe twice...
    case "`echo "$DDCPROBE"`" in
     *edidfail*)
      sleep 1
      DDCPROBE="`ddcprobe`"
     ;;
    esac
    PROFILECHIP="`echo "$DDCPROBE" | grep '^oem: ' | head -n 1 | cut -f 2-4 -d ' ' | tr ' ' '_' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    #v3.95 'eisa:' and 'id:' return fluctuating values on some PCs, so search in this order...
    PROFILEMONITOR="`echo "$DDCPROBE" | grep '^monitorid: ' | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    [ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`echo "$DDCPROBE" | grep '^monitorname: ' | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    [ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`echo "$DDCPROBE" | grep '^monitorrange: ' | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    HARDWAREPROFILE="${PROFILECHIP}${PROFILEMONITOR}"
   fi
   #find out if current xorg.conf matches this profile...
   CURRENTPROFILE="`cat /etc/X11/xorg.conf | grep '^#PuppyHardwareProfile' | cut -f 2 -d '=' | cut -f 1 -d ' '`"
   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}
    #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
   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

#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 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 '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 > /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#
