#!/bin/sh
#(c) Copyright Barry Kauler, April 2013, bkhome.org
#license GPL3 (refer: /usr/share/doc/legal).
#130427 completely rewritten Xorg Wizard. runs without X.
# note, /root/.profile and /usr/sbin/xorgwizard also modified.
#130428 add touchpad support.
#130429 remove /root/xorg.conf.new
#130501 /etc/rc.d/rc.sysinit may create empty /root/xorgwizard-reenter.
#130503 constrain limits of monitor vertical refresh frequency.
#130503 expanded rules to decide whether need to reboot.
#130504 if nv_drv.so present, xorg.conf.new does not have nouveau, and vice-versa.
#130504 customise driver help dlg.
#130504 More resolution choices, including NOTHING.
#130506 backup a prior /etc/X11/xorg.conf.
#130509 advise about typing "xwin [jwm|openbox]".
#130509 fix 130504, nv/nouveau.
#130509 problem with -configure, not detect all possible drivers.
#130513 note, pupdesk.flg code moved from rc.sysinit to init (in intrd).
#130523 when proprietary nvidia driver installed, xorgwizard-cli does not offer it.
#130523 proprietary nvidia installer creates /etc/modprobe.d/nvidia-installer-disable-nouveau.conf
#130524 offer to view content of an alternate xorg.conf file.
#140209 no longer have pupdesk.flg mechanism. using /var/local/quicksetup-test-success, see /usr/sbin/quicksetup.
#140209 no longer using /root/.xorgwizard-reenter or /var/local/quicksetup-pupmode5-autodriver, using /var/local/quicksetup-test-success instead.
#141229 'Xorg -configure' Quirky April, more broken. need to create modesetting and vesa sections.
#150929 do not assume xorg is in /usr/lib
#150930 my laptop has hybrid intel/nvidia video, which is problem.
#151210 handle frugal installation.
#160914 no longer using mouse and keyboard xorg drivers, now evdev, see /etc/X11/xorg.conf.d/10-evdev-puppy.conf

export TEXTDOMAIN=xorgwizard-cli
export OUTPUT_CHARSET=UTF-8
. gettext.sh

if [ $DISPLAY ];then
 echo
 echo "Please exit from X to run this Xorg Wizard."
 exit
fi
if [ "$(readlink /usr/bin/X)" != "Xorg" ];then
 echo
 echo "This script only works for Xorg."
 exit
fi
if [ "$(grep 'xorgwizard-cli' /root/.profile)" = "" ];then
 echo
 echo "/root/.profile is incompatible, aborting."
fi

. /etc/DISTRO_SPECS
. /etc/rc.d/PUPSTATE
. /etc/rc.d/BOOTCONSTRAINED
. /etc/rc.d/functions4puppy4 #choosemousefunc().

if [ "$BOOT_DISABLEXORGWIZARD" = "yes" ];then #refer /etc/rc.d/BOOTCONSTRAINED and 3builddistro.
 echo
 echo "Sorry, the text-mode Xorg Wizard is disabled for this build of Puppy."
 exit
fi

#note, ubuntu precise has 1.11.3, raring has 1.13.0 ...
XORGVER="`Xorg -version 2>&1 | grep '^X Window System Version' | rev | cut -f 1 -d ' ' | rev`" #ex: 1.3.0
[ ! "$XORGVER" ] && XORGVER="`Xorg -version 2>&1 | grep '^X\.Org X Server' | rev | cut -f 1 -d ' ' | rev`"
if vercmp $XORGVER lt 1.11.0; then
 echo
 echo "Sorry, this script is designed for Xorg version 1.11.0 or greater.
However, it might work on earlier versions, we need to find out
-- edit /usr/sbin/xorgwizard-cli and remove this exit-point."
 exit
fi

DLGTITLE="$(gettext 'Puppy Xorg Video Wizard')"

#150929 find where is xorg... ex: /usr/lib64/xorg
XORGPATH="$(find /usr -maxdepth 5 -type d -name drivers | grep '/xorg/modules/drivers' | head -n 1 | rev | cut -f 3- -d '/' | rev)"
if [ ! "$XORGPATH" ];then
 echo "Sorry, cannot find where Xorg is installed, quiting."
 exit
fi

ddcprobe > /tmp/ddcprobe.txt
#weird (ddcprobe is very weird), on some hardware, edid monitor probe fails
#every alternate run of ddcprobe...
case "`cat /tmp/ddcprobe.txt`" in
 *edidfail*)
  sleep 1
  ddcprobe > /tmp/ddcprobe.txt
 ;;
esac

##############################################################
###RE-ENTER: TEST DRIVER###
###########################

if [ -f /var/local/quicksetup-test-success ];then #140209
 cp -f /var/local/quicksetup-test-success /tmp/quicksetup-test-success
 [ ! -s /var/local/quicksetup-test-success ] && rm -f /var/local/quicksetup-test-success
else
 rm -f /tmp/quicksetup-test-success 2>/dev/null
fi

#if this file non-zero, then have reentered script, to test the driver...
if [ -f /var/local/quicksetup-test-success ];then #140209
 CHOSENDRV="$(cat /var/local/quicksetup-test-success | cut -f 1 -d ' ')"
 XLOOP=1

 while [ $XLOOP -ne 0 ];do #testloop
  case "`cat /etc/mousedevice 2>/dev/null`" in
   tty*) MOUSEMSG="$(gettext 'Puppy thinks that you have a serial mouse. However, if your PC has a modern usb or ps/2 mouse, you must choose the <Change mouse> button now.')" ;;
   *)    MOUSEMSG="$(gettext 'Puppy thinks that you have a usb or ps/2 mouse. However, for an old PC that has a serial mouse, you must choose the <Change mouse> button now.')" ;;
  esac
 
  dialog --extra-button --help-button --title "${DLGTITLE}" --ok-label "$(gettext 'TEST X NOW')" --cancel-label "$(gettext 'Change mouse')" --extra-label "$(gettext 'Fallback')" --help-label "$(gettext 'Help')" --yesno "$(gettext 'THE NEXT STEP WILL TEST XORG!')

${MOUSEMSG}

$(gettext 'After choosing <TEST X NOW> button, if the next screen shows a nice dialog box, then X started okay. If the screen is blank or garbage, then failure (In such a case, just press the ENTER key to terminate the test, preferably within the 60 second test timeout).')

$(gettext 'IMPORTANT: If the ENTER key does not terminate the test, press the combination CTRL-ALT-BACKSPACE')

$(gettext 'EMERGENCY SHUTDOWN: If the test hangs your PC, reboot by pressing the reset button, or hold down the power button for 4 seconds to shutdown.')

$(gettext 'Press ENTER key now to test X graphics mode (may take a few secs)...')
$(gettext 'TAB then ENTER to use an old working xorg.conf, or create new xorg.conf...')
$(gettext 'TAB, TAB then ENTER to change the mouse (afterward will return here)...')
$(gettext 'Press ESC key to exit Wizard without testing xorg.conf...')" 0 0

  case $? in
   1) #change the mouse... (then go back up to above dialog)
    choosemousefunc
    continue
   ;;
   2) #help
    dialog --no-cancel --title "${DLGTITLE}: $(gettext 'Help')" --msgbox "$(gettext 'Xorg is the system required for the PC to go into graphical desktop mode.')

$(gettext 'Mouse:')
$(gettext 'Modern PCs have a usb or ps/2 mouse (or touchpad). However, some old PCs have a serial mouse (recognizable by the large rectangular plug), in which case you must choose the <Change mouse> button before continuing with the Wizard.')

$(gettext 'CTRL-ALT-BACKSPACE:')
$(gettext 'This is the standard emergency key combination to terminate Xorg and drop back to the text-mode console. Hold down CTRL and ALT keys then tap the BACKSPACE key. Remember this key combination!')

$(gettext 'Fallback:')
$(gettext 'The Xorg configuration file is /etc/X11/xorg.conf. Choosing this option will offer a choice of all /etc/X11/xorg.conf* files, so if you have previously created one that you know works, you may choose it. Or, you may choose to abort entirely and create a new xorg.conf.')

$(gettext 'Press ENTER key to go back to previous window...')" 0 0
    continue
   ;;
   3) #use old xorg.conf...
    XORGCONFS="$(find /etc/X11 -mindepth 1 -maxdepth 1 -type f -name 'xorg.conf*' | grep -v -E 'conf0|conf-auto|conf-generic|conf.example|xorg.conf$')"
    CNT=1; ALTCONFS0=''
    for ONEXCF in $XORGCONFS
    do
     [ ! -f $ONEXCF ] && continue
     ALTCONFS0="${ALTCONFS0}
${CNT} ${ONEXCF}"
     CNT=`expr $CNT + 1`
    done
    ALTCONFS0="${ALTCONFS0}
${CNT} NONE"
    ALTCONFS1="`echo -n "$ALTCONFS0" | tr '\n' ' '`"
    #130524 offer to view an alternate xorg.conf file...
    echo '#!/bin/sh' > /tmp/xorgwizard-alt-confs
    echo "dialog --stdout --extra-button --title \"${DLGTITLE}\" --ok-label \"$(gettext 'OK')\" --extra-label \"$(gettext 'View')\" --cancel-label \"$(gettext 'Cancel')\" --menu \"$(gettext 'Press UP/DOWN arrow keys to choose an old xorg.conf, or NONE to probe and create a new xorg.conf.')

$(gettext 'Note that after highlighting a file, you can select the <View> button to see the content in a text editor, and afterward come back to this window.')

$(gettext 'After choosing file, press ENTER key to choose <OK> button, or')
$(gettext 'press TAB then ENTER to view content of selected file, or')
$(gettext 'TAB, TAB then ENTER keys to abort and go back to previous window...')\" 0 0 0 $ALTCONFS1" >> /tmp/xorgwizard-alt-confs
    echo 'exit $?' >> /tmp/xorgwizard-alt-confs
    chmod 755 /tmp/xorgwizard-alt-confs
    while true; do #130524
     NUMALTCONF="`/tmp/xorgwizard-alt-confs`"
     altRET=$?
     [ "$NUMALTCONF" = "" ] && continue 2
     if [ $altRET -eq 3 ];then #View
      ALTCONF="`echo "$ALTCONFS0" | grep "^${NUMALTCONF} " | cut -f 2 -d ' '`"
      if [ -f $ALTCONF ];then
       mp $ALTCONF #mp is a text-mode editor in all pups.
       continue
      fi
     fi
     break
    done
    [ $altRET -ne 0 ] && continue
    ALTCONF="`echo "$ALTCONFS0" | grep "^${NUMALTCONF} " | cut -f 2 -d ' '`"
    if [ "$ALTCONF" = "NONE" ];then
     rm -f /var/local/quicksetup-test-success
     exec xorgwizard-cli
    fi
    [ ! -f $ALTCONF ] && continue #precaution.
    cp -f /etc/X11/xorg.conf /etc/X11/xorg.conf-OLD
    cp -f $ALTCONF /etc/X11/xorg.conf #use old working xorg.conf.
    #precaution, recalculate the hardware profile...
    grep -v '^#PuppyHardwareProfile' /etc/X11/xorg.conf > /tmp/xorg.conf.tmp2
    PROFILECHIP="`grep -m1 '^oem: ' /tmp/ddcprobe.txt | cut -f 2-4 -d ' ' | tr ' ' '_' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    #'eisa:' and 'id:' return fluctuating values on some PCs, so search in this order...
    PROFILEMONITOR="`grep '^monitorid: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    [ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^monitorname: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    [ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^monitorrange: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
    echo "#PuppyHardwareProfile=${PROFILECHIP}${PROFILEMONITOR}" >> /tmp/xorg.conf.tmp2
    cp -f /tmp/xorg.conf.tmp2 /etc/X11/xorg.conf
    #create a copy of xorg.conf with the profile in the filename...
    cp -af /etc/X11/xorg.conf /etc/X11/xorg.conf.${PROFILECHIP}${PROFILEMONITOR}
    clear
    echo -en "\\033[1;32m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
    echo "$(gettext 'File:') ${ALTCONF}"
    echo "$(gettext 'Has been copied to:') /etc/X11/xorg.conf"
    echo "$(gettext 'Also backed up as:') /etc/X11/xorg.conf.${PROFILECHIP}${PROFILEMONITOR}"
    echo -n "$(gettext 'Type "xwin" (then ENTER key) to start X...')"
    echo -e "\\033[0;39m"
    exit
   ;;
   0) #test X now.
    break
   ;;
   *) #abort (maybe pressed esc key)
    touch /tmp/bootcnt.txt #prevent X from starting (see /root/.profile).
    rm -f /var/local/quicksetup-test-success #so next run xorgwizard-cli, creates new xorg.conf.
    clear
    echo -en "\\033[1;36m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
    echo "$(gettext 'You have exited from the Xorg Wizard without testing the configuration file /etc/X11/xorg.conf.')"
    echo -n "$(gettext 'Type "xwin" (then ENTER key) to start X (the graphical desktop) now, or "xorgwizard" to re-run the Xorg Wizard.')"
    echo -e "\\033[0;39m"
    echo "$(gettext 'Note, type "xwin jwm" or "xwin openbox" if you have both of these window managers installed and you want to change from the current one. Ditto for any other installed window manager.')"
    exit
   ;;
  esac
 done
 
 ###TEST XORG###
 export MONCHOICES='' #previous xorgwizard set this, read in xinitrc_test.
 xinit /usr/sbin/xinitrc_test -- /usr/bin/Xorg :0
 eval "`cat /tmp/xorgwizard_initrc_test_results`" #results from xinitrc_test
 #...XTEST, YTEST, HSTEST, VRTEST.
 
 load_consolefont #it seems have to reload console font after exit from X.

 dialog --extra-button --no-collapse --title "${DLGTITLE}" --ok-label "$(gettext 'FINISHED')" --cancel-label "$(gettext 'Tweak')" --extra-label "Abort" --yesno "$(gettext 'Report on X test:')
                  $(eval_gettext "Resolution:           \${XTEST}x\${YTEST} pixels")
                  $(eval_gettext "Horizontal frequency: \${HSTEST} KHz")
                  $(eval_gettext "Refresh frequency:    \${VRTEST} Hz")
                  $(eval_gettext "Video driver:         \${CHOSENDRV}")

$(gettext 'If you are reporting success, great, but if the display was not quite right, say displaced or distorted, you now have the option of tweaking various parameters, even choose a different video driver. Ditto if testing X was an abysmal failure.')

$(gettext 'Press ENTER key if test was okay...')
$(gettext 'TAB then ENTER to abort and go back to main window...')
$(gettext 'TAB, TAB then ENTER to tweak parameters & retest X...')" 0 0
 
 case $? in
  0) #test was ok.
   rm -f /var/local/quicksetup-test-success
   clear
   echo
   echo -en "\\033[1;32m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
   echo "$(gettext 'The Puppy Xorg Wizard has been run, presumably successfully.')
$(gettext 'If so, type "xwin" (then ENTER key) to start Xorg and the graphical desktop.')
$(gettext 'Otherwise, you may type "xorgwizard" to re-run the Wizard...')"
   echo -e "\\033[0;39m"
   echo "$(gettext 'Note, type "xwin jwm" or "xwin openbox" if you have both of these window managers installed and you want to change from the current one. Ditto for any other installed window manager.')"
   exit
  ;;
  3) #abort
   exec xorgwizard-cli ###REENTER###
  ;;
  1) #tweak
   dialog --title "${DLGTITLE}" --msgbox "$(gettext 'The next step will be to open /etc/X11/xorg.conf in a text editor. Various parameters can be modified, then the file saved, then exit the editor. Please note that this is a text-mode editor that does not work with a mouse.')

$(gettext 'Displaced:')
$(gettext "The most common problem is the image displaced/squeezed/distorted. Often this is due to a wrong vertical refresh frequency (number of times per second that the screen gets re-drawn). You may experiment with the 'VertRefresh' range. Note, 60Hz is usually OK for LCD screens. Older CRT screens may flicker at 60Hz, usually need at least 70Hz.")" 0 0
   mp /etc/X11/xorg.conf
   exec xorgwizard-cli ###REENTER###
  ;;
 esac

 exit
fi

#####################################################################
###create /etc/X11/xorg.conf###
###############################

#during woof build, may have put some drivers here...
cp -a -f --remove-destination /usr/lib/x/drivers-alternate/* ${XORGPATH}/modules/drivers/ 2> /dev/null
rm -f /usr/lib/x/drivers-alternate/* 2> /dev/null

#130428 touchpad support...
FLAGTOUCHPAD="$(grep -E 'Elantech|Alps|Synaptics' /proc/bus/input/devices)"
if [ "$FLAGTOUCHPAD" ];then
 if [ "`lsmod | grep '^evdev'`" == "" ];then
  modprobe evdev
  [ "`grep '^modprobe evdev' /etc/rc.d/rc.local`" == "" ] && echo "modprobe evdev" >> /etc/rc.d/rc.local
 fi
fi

#find out current video basics...
KMS_i915="$(grep -o 'modeset=[01]' /etc/modprobe.d/i915.conf | cut -f 2 -d '=')"
KMS_nouveau="$(grep -o 'modeset=[01]' /etc/modprobe.d/nouveau.conf | cut -f 2 -d '=')"
KMS_radeon="$(grep -o 'modeset=[01]' /etc/modprobe.d/radeon.conf | cut -f 2 -d '=')"
KMS_all="${KMS_i915}${KMS_nouveau}${KMS_radeon}"
KERNVER="$(uname -r)"
GPUDRM_PATH="$(find /lib/modules/${KERNVER}/kernel/drivers -type f -name i915.ko | sed -e 's%/i915\.ko$%%' -e 's%/i915$%%')"
#...ex: GPUDRM_PATH=/lib/modules/3.8.4/kernel/drivers/gpu/drm
GPUDRM_MODS="$(ls ${GPUDRM_PATH}/*/*.ko | rev | cut -f 1 -d '/' | cut -f 2 -d '.' | rev)" #list all gpu drm modules.
ALL_LOADED_MODS="$(lsmod | grep -v '^Module' | cut -f 1 -d ' ')"
echo "$ALL_LOADED_MODS" > /tmp/xorgwizard-loaded-mods
echo "$GPUDRM_MODS" > /tmp/xorgwizard-all-gpudrm-mods
GPUDRM_LOADED_MODS="$(grep -f /tmp/xorgwizard-loaded-mods -w /tmp/xorgwizard-all-gpudrm-mods)"
#...ex: i915\nnouveau\nttm\n

#130523 difficult situation if proprietary nvidia installer has created this file, with these contents:
## generated by nvidia-installer
#blacklist nouveau
#options nouveau modeset=0
if [ -f /etc/modprobe.d/nvidia-installer-disable-nouveau.conf ];then
 if [ "$(echo "$GPUDRM_LOADED_MODS" | grep '^nouveau$')" = "" ];then
  #bootup has occurred with this file in place, so nouveau was blacklisted.
  echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf
  KMS_nouveau="0"
 else
  #have installed proprietary nvidia driver but not yet rebooted.
  true
 fi
 rm -f /etc/modprobe.d/nvidia-installer-disable-nouveau.conf
fi

#process the above info a bit...
ACTIVE_KMS_i915="0"; ACTIVE_KMS_nouveau="0"; ACTIVE_KMS_radeon="0"
[ "$KMS_i915" = "1" ] && [ "$(echo "$GPUDRM_LOADED_MODS" | grep '^i915$')" != "" ] && ACTIVE_KMS_i915="1"
[ "$KMS_nouveau" = "1" ] && [ "$(echo "$GPUDRM_LOADED_MODS" | grep '^nouveau$')" != "" ] && ACTIVE_KMS_nouveau="1"
[ "$KMS_radeon" = "1" ] && [ "$(echo "$GPUDRM_LOADED_MODS" | grep '^radeon$')" != "" ] && ACTIVE_KMS_radeon="1"
ACTIVE_KMS_PTN="${ACTIVE_KMS_i915}${ACTIVE_KMS_nouveau}${ACTIVE_KMS_radeon}"

###experiments###
##extract sections from xorg conf file...
#sPTN='/^Section "InputDevice"/,/^EndSection/p' #this is a multi-line block find expression.
##N means read next line and append to the pattern-space...
#sPTN='{
#N
#/^Section "InputDevice".*"Keyboard0"/,/^EndSection/p
#}'
##...doesn't always work. try this...
#sPTN='/^Section "InputDevice"/,/^EndSection/ { /"Mouse0"/,/^EndSection/p; }'
##...yes, this works (but doesn't print the first Section... line)
##note, requires -n param for sed.
#
##http://sed.sourceforge.net/sedfaq4.html#s4.20
#sPTN='
#:t
#/^Section "InputDevice"/,/^EndSection/ {
# /^EndSection/!{
#  $!{
#   N;
#   bt
#  }
# }
# /"Mouse0"/p;
#}
#'
##...no. 
#
##this one finds a paragraph containing a regex... WORKS!
##very good, the regex spans the entire paragraph...
#sPTN='/./{H;$!d;};x;/"InputDevice".*"Keyboard0"/!d'
##note, do not use -n param for sed...
#
#sed  "$sPTN" /etc/X11/xorg.conf

cp -f /etc/X11/xorg.conf0 /tmp/xorg.conf.tmp
#echo "" >> /tmp/xorg.conf.tmp

clear
echo -en "\\033[1;35m" #34=blue, 33=yellow, 32=green, 31=red, 35=purple, 36=aquablue, 38=black.
echo -n "$(gettext 'Probing video hardware, please wait...')"
echo -e "\\033[0;39m"

if [ "$FLAGTOUCHPAD" ];then #130428
 OLD1='Section "Module"'
 NEW1='Section "Module"\n	Load "synaptics" #loadsynaptics'
 tPTN="s%${OLD1}%${NEW1}%"
 sed -i "$tPTN" /tmp/xorg.conf.tmp
fi

#130428  160914 now have /etc/X11/xorg.conf.d/10-evdev-puppy.conf for input devices...
echo 'Section "ServerLayout"
	Identifier "Default Layout"
	Screen "Screen0" 0 0
#	InputDevice "Keyboard0" "CoreKeyboard"
#	InputDevice "Mouse0" "CorePointer"' >> /tmp/xorg.conf.tmp
#[ "$FLAGTOUCHPAD" ] && echo '	InputDevice "SynapticsMouse" "AlwaysCore" #serverlayoutsynaptics' >> /tmp/xorg.conf.tmp
echo -e 'EndSection' >> /tmp/xorg.conf.tmp

#autoprobe...
Xorg -configure > /tmp/xorgprobe.txt 2>&1 #... config in /root/xorg.conf.new

#150930 /root/xorg.conf.new seems to find the actual video hardware, my laptop has bybrid intel/nvidia video,
#and defaults to using intel, but turning on kms for the nouveau kernel driver stuffs things up.
#this code is only useful where the interfaces are of two different types, such as intel and nvidia.
DISABLESECONDDRVR=""
c0PTN='/./{H;$!d;};x;/Section "Device".*Identifier  "Card0"/!d'
c1PTN='/./{H;$!d;};x;/Section "Device".*Identifier  "Card1"/!d'
c0SECT="$(sed "$c0PTN" /root/xorg.conf.new)"
c1SECT="$(sed "$c1PTN" /root/xorg.conf.new)"
c0DRVR="$(echo "$c0SECT" | tr '\t' ' ' | tr -s ' ' | grep '^ Driver "' | cut -f 2 -d '"')" #ex: intel
c1DRVR="$(echo "$c1SECT" | tr '\t' ' ' | tr -s ' ' | grep '^ Driver "' | cut -f 2 -d '"')" #ex: nouveau
[ "$c0DRVR" == "$c1DRVR" ] && c1DRVR=""
if [ "$c0DRVR" != "" -a "$c1DRVR" != "" ];then
 c0EX=""; c1EX=""
 case $c0DRVR in
  nouveau|nv) c0EX="(nVidia)" ;;
  r128|mach64|radeon) c0EX="(ATI)" ;;
 esac
 case $c1DRVR in
  nouveau|nv) c1EX="(nVidia)" ;;
  r128|mach64|radeon) c1EX="(ATI)" ;;
 esac
 twoMSG0="$(gettext 'Xorg Video Wizard')"
 twoMSG1="$(gettext 'This computer seems to have two video interfaces:')"
 twoMSG2="$(gettext 'To avoid conflict, please choose which one to use')"
 twoMSG3="$(gettext '(or press ESC key to leave both enabled)')"
 twoMSG9="${twoMSG1}

  ${c0DRVR} ${c0EX}
  ${c1DRVR} ${c1EX}

${twoMSG2}
${twoMSG3}"
 dialog --yes-label "${c0DRVR}" --no-label "${c1DRVR}" --title "${twoMSG0}" --yesno "${twoMSG9}" 0 0
 case $? in
  0) #ok/yes
   sed '/^Section "Device"/,/^$/d' /root/xorg.conf.new > /tmp/xorg.conf.new-cut #remove all Device sections.
   mv -f /tmp/xorg.conf.new-cut /root/xorg.conf.new
   echo "$c0SECT" >> /root/xorg.conf.new
   DISABLESECONDDRVR="$c1DRVR"
  ;;
  1) #cancel/no
   sed '/^Section "Device"/,/^$/d' /root/xorg.conf.new > /tmp/xorg.conf.new-cut
   mv -f /tmp/xorg.conf.new-cut /root/xorg.conf.new
   echo "$c1SECT" >> /root/xorg.conf.new
   DISABLESECONDDRVR="$c0DRVR"
  ;;
 esac 
fi

#now edit sections from /root/xorg.conf.new and append to /etc/X11/xorg.conf...

###Keyboard### 160914 removed...
#XKEYMAP='us'
#RETVALS="`keymap-set --xopt`"
#eval "$RETVALS" #ex: XKBMODEL="pc102", XKBLAYOUT="us", XKBVARIANT=""
#[ "$XKBLAYOUT" = "" ] && XKBLAYOUT='us'
#[ "$XKBMODEL" = "" ] && XKBMODEL='pc102'
#sPTN='/./{H;$!d;};x;/Section "InputDevice".*"Keyboard0"/!d'
#ASECTION="$(sed "$sPTN" /root/xorg.conf.new | head -n -1)" #leave off EndSection
#echo "$ASECTION" >> /tmp/xorg.conf.tmp
#echo "	Option      \"XkbRules\" \"xorg\"
#	Option      \"XkbModel\" \"${XKBMODEL}\"
#	Option      \"XkbLayout\" \"${XKBLAYOUT}\" #xkeymap0" >> /tmp/xorg.conf.tmp
#[ "$XKBVARIANT" ] && echo "	Option         \"XkbVariant\" \"$XKBVARIANT\"" >> /tmp/xorg.conf.tmp
#echo -e 'EndSection' >> /tmp/xorg.conf.tmp

###Mouse### 160914 removed...
#sPTN='/./{H;$!d;};x;/Section "InputDevice".*"Mouse0"/!d'
#ASECTION="$(sed "$sPTN" /root/xorg.conf.new | head -n -1 | grep -v -E 'Emulate3|ZAxisMapping|Protocol')" #leave off EndSection
#echo "$ASECTION" >> /tmp/xorg.conf.tmp
#case "`cat /etc/mousedevice 2>/dev/null`" in 
# input/mice) echo '	Option	    "Protocol" "IMPS/2" #mouse0protocol' >> /tmp/xorg.conf.tmp ;;
# *ttyS*) echo '	Option	    "Protocol" "Microsoft" #mouse0protocol' >> /tmp/xorg.conf.tmp ;;
# *) echo '	Option	    "Protocol" "auto" #mouse0protocol' >> /tmp/xorg.conf.tmp ;;
#esac
#case "`cat /etc/xextraoptions 2>/dev/null`" in 
# *2button*)
#  echo '	Option      "Emulate3Buttons"
#	Option      "Emulate3Timeout" "50"' >> /tmp/xorg.conf.tmp
# ;;
# *)
#  echo '	#Option      "Emulate3Buttons"
#	#Option      "Emulate3Timeout" "50"' >> /tmp/xorg.conf.tmp
# ;;
#esac
#case "`cat /etc/mousebuttons 2>/dev/null`" in
# 5)  echo '	Option      "ZAxisMapping" "4 5" #scrollwheel' >> /tmp/xorg.conf.tmp ;;
# *)  echo '	#Option      "ZAxisMapping" "4 5" #scrollwheel' >> /tmp/xorg.conf.tmp ;;
#esac
#echo -e 'EndSection' >> /tmp/xorg.conf.tmp
#
#if [ "$FLAGTOUCHPAD" ];then #130428
# echo '
#Section "InputDevice"
#	Identifier "SynapticsMouse"
#	Driver "synaptics"
#	Option "SHMConfig" "on"
#EndSection' >> /tmp/xorg.conf.tmp
#fi

###Monitor###
sPTN='/./{H;$!d;};x;/Section "Monitor".*"Monitor0"/!d'
ASECTION="$(sed "$sPTN" /root/xorg.conf.new | head -n -1 | grep -v -E 'HorizSync|VertRefresh')" #leave off EndSection
echo "$ASECTION" >> /tmp/xorg.conf.tmp
echo "	#HorizSync    HORIZSYNC0
	VertRefresh  VERTREFRESH0
	#UseModes     \"Modes0\" #monitor0usemodes
	Option      \"PreferredMode\" \"PREFERREDMODE0\"" >> /tmp/xorg.conf.tmp
echo -e 'EndSection\n' >> /tmp/xorg.conf.tmp
echo "Section \"Modes\"
	Identifier \"Modes0\"
	#modes0modeline0
EndSection" >> /tmp/xorg.conf.tmp

###Video card###

#141229 have to create these (Xorg -configure broken)...
if [ -f ${XORGPATH}/modules/drivers/vesa_drv.so ];then
 if [ "$(grep 'Driver *"vesa"' /root/xorg.conf.new)" = "" ];then
  echo '
Section "Device"
        ### Available Driver options are:-
        ### Values: <i>: integer, <f>: float, <bool>: "True"/"False",
        ### <string>: "String", <freq>: "<f> Hz/kHz/MHz",
        ### <percent>: "<f>%"
        ### [arg]: arg optional
        #Option     "ShadowFB"           	# [<bool>]
        #Option     "DefaultRefresh"     	# [<bool>]
        #Option     "ModeSetClearScreen" 	# [<bool>]
        #Option     "NoDDC"              	# [<bool>]
	Identifier  "Card88"
	Driver      "vesa"
EndSection' >> /root/xorg.conf.new
 fi
fi
if [ -f ${XORGPATH}/modules/drivers/modesetting_drv.so ];then
 if [ "$(grep 'Driver *"modesetting"' /root/xorg.conf.new)" = "" ];then
  echo '
Section "Device"
        ### Available Driver options are:-
        ### Values: <i>: integer, <f>: float, <bool>: "True"/"False",
        ### <string>: "String", <freq>: "<f> Hz/kHz/MHz",
        ### <percent>: "<f>%"
        ### [arg]: arg optional
        #Option     "SWcursor"           	# [<bool>]
        #Option     "kmsdev"             	# <str>
        #Option     "ShadowFB"           	# [<bool>]
	Identifier  "Card89"
	Driver      "modesetting"
EndSection' >> /root/xorg.conf.new
 fi
fi

#130504 peculiar, if nv present, xorg.conf.new does not have nouveau, so add it...
if [ "$DISABLESECONDDRVR" != "nouveau" -a "$DISABLESECONDDRVR" != "nv" ];then #150930
 if [ -f ${XORGPATH}/modules/drivers/nouveau_drv.so ];then
  if [ "$(grep 'Driver *"nouveau"' /root/xorg.conf.new)" = "" ];then
   if [ "$(grep 'Driver *"nv"' /root/xorg.conf.new)" != "" ];then #130509 fix logic.
    echo '
Section "Device"
        #Option     "SWcursor"           	# [<bool>]
        #Option     "HWcursor"           	# [<bool>]
        #Option     "NoAccel"            	# [<bool>]
        #Option     "ShadowFB"           	# [<bool>]
        #Option     "VideoKey"           	# <i>
        #Option     "WrappedFB"          	# [<bool>]
        #Option     "GLXVBlank"          	# [<bool>]
        #Option     "ZaphodHeads"        	# <str>
        #Option     "PageFlip"           	# [<bool>]
        #Option     "SwapLimit"          	# <i>
        #Option     "AsyncUTSDFS"        	# [<bool>]
	Identifier  "Card91"
	Driver      "nouveau"
EndSection
' >> /root/xorg.conf.new
   fi
  fi
 fi
 #or vice-versa...
 if [ -f ${XORGPATH}/modules/drivers/nv_drv.so ];then
  if [ "$(grep 'Driver *"nv"' /root/xorg.conf.new)" = "" ];then
   if [ "$(grep 'Driver *"nouveau"' /root/xorg.conf.new)" != "" ];then #130509 fix logic.
    echo '
Section "Device"
        #Option     "SWcursor"           	# [<bool>]
        #Option     "HWcursor"           	# [<bool>]
        #Option     "NoAccel"            	# [<bool>]
        #Option     "ShadowFB"           	# [<bool>]
        #Option     "UseFBDev"           	# [<bool>]
        #Option     "Rotate"             	# [<str>]
        #Option     "VideoKey"           	# <i>
        #Option     "FlatPanel"          	# [<bool>]
        #Option     "FPDither"           	# [<bool>]
        #Option     "CrtcNumber"         	# <i>
        #Option     "FPScale"            	# [<bool>]
        #Option     "FPTweak"            	# <i>
        #Option     "DualHead"           	# [<bool>]
	Identifier  "Card90"
	Driver      "nv"
EndSection' >> /root/xorg.conf.new
   fi
  fi
 fi
fi

#130509 unfortunately -configure option does not work very well, i don't think it has been properly
#updated by the developers. I have a pc with sis video, automatic startup loads the sis_drv.so Xorg driver,
#and it works, but -configure does not offer 'sis'. not happy, but will attempt a workaround...
XAUTODRV=''
if [ -s /tmp/quicksetup-test-success ];then #created in quicksetup. 140209 backup at entry, in /tmp
 XAUTODRV="`cat /var/local/quicksetup-test-success | cut -f 1 -d ' '`"
 if [ -f ${XORGPATH}/modules/drivers/${XAUTODRV}_drv.so ];then
  autoPTN="Driver *\"${XAUTODRV}\""
  if [ "$(grep "$autoPTN" /root/xorg.conf.new)" = "" ];then
   echo "
Section \"Device\"
	Identifier  \"Card92\"
	Driver      \"${XAUTODRV}\"
EndSection" >> /root/xorg.conf.new
  fi
 fi
fi

#130523 when proprietary nvidia driver installed, xorgwizard-cli does not offer it,
#only offers nouvea, modesetting and vesa. note, the official installer offers to
#blacklist nouvea kernel module in /etc/modprobe.d, however in case that is not done...
if [ -f ${XORGPATH}/modules/drivers/nvidia_drv.so ];then
 if [ "$(grep 'Driver *"nvidia"' /root/xorg.conf.new)" = "" ];then
  if [ "$(grep 'Driver *"nouveau"' /root/xorg.conf.new)" != "" ];then
   echo '
Section "Device"
	Identifier  "Card93"
	Driver      "nvidia"
EndSection' >> /root/xorg.conf.new
  fi
 fi
fi


#how do we handle all the card sections? ...
echo -n "" > /tmp/xorgwizard-driverlist0
for CARDNUM in 0 1 2 3 4 5 6 88 89 90 91 92 93
do
 sPTN='/./{H;$!d;};x;/Section "Device".*"Card'${CARDNUM}'"/!d'
 ASECTION="$(sed "$sPTN" /root/xorg.conf.new | head -n -1)" #leave off EndSection
 [ ! "$ASECTION" ] && continue
 #echo "$ASECTION" >> /tmp/xorg.conf.tmp
 #create a list and offer choice to user...
 XORGDRIVER="$(echo "$ASECTION" | grep -E '^\W+Driver' | cut -f 2 -d '"')" #'geany
 [ "$DISABLESECONDDRVR" == "$XORGDRIVER" ] && continue #150930
 [ ! -f ${XORGPATH}/modules/drivers/${XORGDRIVER}_drv.so ] && continue
 EXMSG='driver'; EX2MSG=''
 MSGKMS="$(gettext 'driver, needs KMS')"
 MSGNOKMS="$(gettext 'driver, no KMS')"
 MSGREBOOT="$(gettext '(requires reboot)')"
 MSGUNACCEL="$(gettext 'Unaccelerated driver')"
 case $XORGDRIVER in
  vesa)
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="${MSGUNACCEL}"
  ;;
  nouveau)
   [ "$ACTIVE_KMS_PTN" != "010" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="NVIDIA ${MSGKMS}"
  ;;
  nv)
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="$(gettext 'Simple NVIDA driver')"
  ;;
  nvidia)
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="$(gettext 'NVIDIA proprietary driver')"
  ;;
  modesetting)
   #i think requires all of the kernel kms drivers enabled...
   #150930 need to consider the blacklisted second driver...
   #[ "$KMS_all" != "111" ] && EX2MSG=" ${MSGREBOOT}"
   if [ "$DISABLESECONDDRVR" ];then
    case "$DISABLESECONDDRVR" in
     nouveau|nv)    [ "$ACTIVE_KMS_nouveau" = "1" ] && EX2MSG=" ${MSGREBOOT}" ;;
     intel|i810)    [ "$ACTIVE_KMS_i915" = "1" ] && EX2MSG=" ${MSGREBOOT}"    ;;
     radeon|r128|mach64|fglrx|ati) [ "$ACTIVE_KMS_radeon" = "1" ] && EX2MSG=" ${MSGREBOOT}" ;;
    esac
   fi
   EXMSG="${MSGUNACCEL}"
  ;;
  intel)
   [ "$ACTIVE_KMS_PTN" != "100" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="Intel ${MSGKMS}"
  ;;
  radeon)
   [ "$ACTIVE_KMS_PTN" != "001" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="ATI Radeon ${MSGKMS}"
  ;;
  radeonhd) #old abandoned radeon non-kms driver.
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="$(gettext 'Old ATI Radeon driver')"
  ;;
  ati|mach64|r128)
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="ATI ${MSGNOKMS}"
  ;;
  fglrx) #does not work with kms...
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
   EXMSG="$(gettext 'ATI proprietary driver')"
  ;;
  fbdev) continue ;;
  *)
   [ "$ACTIVE_KMS_PTN" != "000" ] && EX2MSG=" ${MSGREBOOT}"
  ;;
 esac
 echo "$CARDNUM $XORGDRIVER \"${EXMSG}${EX2MSG}\"" >> /tmp/xorgwizard-driverlist0
done
DRIVERLIST="$(sort --key=2,2 --unique /tmp/xorgwizard-driverlist0 | cut -f 2- -d ' ' | tr '\n' ' ')"

#130504 customise driver help dlg...
ACCELDRVHELP="$(gettext 'Accelerated drivers are designed for specific video hardware. Basically, they are much faster than the unaccelerated drivers. They may also offer additional configuration features.')"
DRVCHOICES="$(cut -f 2 -d ' ' /tmp/xorgwizard-driverlist0 | tr '\n' ' ')"
case "$DRVCHOICES" in
 *nv*|*nouveau*|*nvidia*) #note \Z7 is reverse text, \Zn returns to normal...
  ACCELDRVHELP="${ACCELDRVHELP}

\Z7NVIDIA\Zn
nv:      $(gettext 'This is the simplest accelerated driver. Works without KMS')
nouveau: $(gettext 'Most sophisticated accelerated driver. Requires KMS')
nvidia:  $(gettext 'If installed, this is the commercial driver. Works without KMS')"
 ;;
esac
case "$DRVCHOICES" in
 *intel*|*i810*)
  ACCELDRVHELP="${ACCELDRVHELP}

\Z7Intel\Zn
intel: $(gettext 'Intel accelerated driver. Requires KMS')
i810:  $(gettext 'If installed, for some older hardware. Works without KMS')"
 ;;
esac
case "$DRVCHOICES" in
 *ati*|*r128*|*mach64*|*radeon*|*fglrx*)
  ACCELDRVHELP="${ACCELDRVHELP}

\Z7ATI\Zn
r128: mach64: $(gettext 'These are accelerated drivers for certain ATI hardware.')
radeon:       $(gettext 'Accelerated driver for ATI Radeon hardware. Requires KMS')
radeonhd:     $(gettext 'If installed, older accelerated driver. Without KMS')
fglrx:        $(gettext 'If installed, accelerated commercial driver. Without KMS')"
 ;;
esac

DRVDLGMSG="$(gettext 'Please use UP/DOWN arrow keys to choose a Xorg driver, then press ENTER key...')
$(gettext 'Or, press TAB (or RIGHT arrow) then ENTER to exit from the Wizard...')
$(gettext 'If uncertain, press TAB, TAB then ENTER to choose <Help>...')"
echo '#!/bin/sh' > /tmp/xorgwizard-driverlist-choose.sh
echo "dialog --stdout --title \"${DLGTITLE}\" --help-button --help-label "$(gettext 'Help')" --menu \"${DRVDLGMSG}\" 0 0 0 ${DRIVERLIST}" >> /tmp/xorgwizard-driverlist-choose.sh
echo 'exit $?' >> /tmp/xorgwizard-driverlist-choose.sh
chmod 755  /tmp/xorgwizard-driverlist-choose.sh
while [ 1 -eq 1 ];do
 xCHOSENDRV="`/tmp/xorgwizard-driverlist-choose.sh 2>/dev/null`"
 RETVAL=$?
 CHOSENDRV="`echo -n "$xCHOSENDRV" | cut -f 1 -d '_'`" #get rid of _NOKMS
 case $RETVAL in
  0) break ;;
  2) #help
   dialog --colors --no-cancel --title "${DLGTITLE}: $(gettext 'Help')" --msgbox "$(gettext 'The Xorg Wizard has probed the computer and determined that any of these drivers may be suitable. Choose that which seems most appropriate. If a driver does not work, at worst even hangs the PC, you will be able to re-run the Wizard and choose another driver.')

${ACCELDRVHELP}

\Z7$(gettext 'Generic')\Zn
$(gettext "Fallbacks are the generic unaccelerated drivers 'vesa' and 'modesetting', that should work for all video hardware. They have limitations, such as slowness and no full-screen video. The 'vesa' driver can only use a VESA standard resolution (which may not match your wide-screen monitor), however the 'modesetting' driver can be set to the native resolution of the monitor.")" 0 0
   continue
  ;;
  *) exit ;; #maybe pressed esc key.
 esac
done

#write chosen card section to xorg.conf...
CARDNUM="$(cut -f 1 -d '"'  /tmp/xorgwizard-driverlist0 | grep -w "$CHOSENDRV" | head -n 1 | cut -f 1 -d ' ')" #'geany
sPTN='/./{H;$!d;};x;/Section "Device".*"Card'${CARDNUM}'"/!d'
ASECTION="$(sed "$sPTN" /root/xorg.conf.new | head -n -1 | grep -v -E 'BusID|Identifier|Driver')" #leave off EndSection
echo "$ASECTION" >> /tmp/xorg.conf.tmp
echo '	Identifier  "card0"' >> /tmp/xorg.conf.tmp
echo '	Driver      "'"${CHOSENDRV}"'" #card0driver' >> /tmp/xorg.conf.tmp
echo -e 'EndSection\n' >> /tmp/xorg.conf.tmp

###Screen section###
HORIZSYNC=""; VERTREFRESH=""; MONCHOICES=""
#modes supported by monitor... format of each line: 1024x768@75
if [ "$CHOSENDRV" != "vesa" ];then
 MONXY0="$(grep '^dtiming:' /tmp/ddcprobe.txt | cut -f 2 -d ' ' | cut -f 1 -d '@' | sed -e 's%$% "Recommended choice"%')"
 #get too many weird resolutions, maybe better just only allow these...
 MONXY1="$(grep '^timing:' /tmp/ddcprobe.txt | grep -E -v 'Apple|8514A|Mac II|\(XGA2\)' | grep -E ' 640x480@| 800x480@| 800x600@| 1024x600@| 1024x768@| 1280x768@| 1280x800@| 1280x1024@| 1366x768@| 1400x1050@| 1440x900@| 1600x900@| 1600x1200@| 1680x1050@| 1920x1080@| 1920x1200@' | cut -f 2 -d ' ' | cut -f 1 -d '@' | sed -e 's%$% "Resolution supported by monitor"%')"
fi
MONXY2="$(grep '^mode:' /tmp/ddcprobe.txt | cut -f 2 -d ' ' | cut -f 1,2 -d 'x' | sed -e 's%$% "VESA standard resolution"%')"
MONXY3="$(echo -e '800x600\n1024x768\n1280x1024' | sed -e 's%$% "VESA standard resolution"%')"
XYCHOICES="$(echo -e "${MONXY0}\n${MONXY2}\n${MONXY1}\n${MONXY3}" | sed -e 's%^$%%' | sort --field-separator=x --key=1,1 --unique --numeric-sort | tr '\n' ' ')"

#dialog to offer resolutions... 130504 add 'NOTHING' option...
XGUESS="$(gettext 'Let Xorg guess it')"
RESDLGMSG="$(gettext "Screen resolutions are listed below, in the format horizontal x vertical pixels. One of these will be best suited to your monitor. If the Wizard offers a 'recommended' resolution, choose that.")
NOTHING: $(gettext 'This option means leave it up to Xorg to try and guess the most appropriate resolution -- this usually works well.')

$(gettext 'Use the UP/DOWN arrow keys to choose a resolution, then press ENTER key...')
$(gettext 'Or, press TAB then ENTER for more resolutions to choose from...')"
echo '#!/bin/sh' > /tmp/xorgwizard-resolution.sh
echo "dialog --stdout --title \"${DLGTITLE}\" --ok-label \"$(gettext 'OK')\" --cancel-label \"$(gettext 'More')\" --menu \"${RESDLGMSG}\" 0 0 0 ${XYCHOICES} NOTHING \"${XGUESS}\"" >> /tmp/xorgwizard-resolution.sh
echo 'exit $?' >> /tmp/xorgwizard-resolution.sh
chmod 755 /tmp/xorgwizard-resolution.sh
while true ; do #130504 second dlg with more choices...
 FINALXY="$(/tmp/xorgwizard-resolution.sh)"
 RESRET=$?
 [ $RESRET -ne 0 -a $RESRET -ne 1 ] && exit
 if [ $RESRET -eq 1 ];then #More
  RESHI="$(gettext 'Hi-res monitor')"
  RESVHI="$(gettext 'Very hi-res monitor')"
  RESNONV="$(gettext 'Non-VESA, widescreen')"
  MOREDLG="$(gettext 'Use the UP/DOWN arrow keys to choose a resolution, then press ENTER key...')
$(gettext 'Or, press TAB then ENTER to go back to previous window...')"
  FINALXY="`dialog --stdout --title "${DLGTITLE}" --ok-label "$(gettext 'OK')" --cancel-label "$(gettext 'Go back')" --menu "${MOREDLG}" 0 0 0  640x480 "$(gettext 'Very poor, not usable')" 800x600 "$(gettext 'Minimum usable by Puppy')" 1024x600 "." 1024x768 "$(gettext 'Good, works with most monitors')" 1280x800 "${RESNONV}" 1280x1024 "${RESHI}" 1366x768 "${RESNONV}" 1400x1050 "${RESHI}" 1440x900 "${RESNONV}" 1600x900 "${RESNONV}" 1600x1200 "${RESVHI}" 1680x1050 "${RESVHI}" 1920x1080 "${RESVHI}" 1920x1200 "${RESVHI}"`"
  [ $? -ne 0 ] && continue
 fi
 break
done

MONFREQ="`grep -F 'monitorrange:' /tmp/ddcprobe.txt | cut -f 2-10 -d ' '`"
if [ "$MONFREQ" ];then
 HORIZSYNC="`echo -n "$MONFREQ" | cut -f 1 -d ','`"
 VERTREFRESH="`echo -n "$MONFREQ" | cut -f 2 -d ',' | tr -d ' '`"
 #130503 my "white tower" with crt monitor: "monitorrange: 30-95, 50-160"
 #however, previous experience is that the upper limit of 160 is too high...
 #i don't think much of 50 either...
 if [ "$(echo -n "$VERTREFRESH" | grep '\-')" != "" ];then
  LOWERLIMIT="$(echo -n "$VERTREFRESH" | cut -f 1 -d '-')"
  UPPERLIMIT="$(echo -n "$VERTREFRESH" | cut -f 2 -d '-')"
  if vercmp $LOWERLIMIT lt 59; then LOWERLIMIT="59" ; fi #use vercmp in case of decimal point.
  if vercmp $UPPERLIMIT gt 86; then UPPERLIMIT="86" ; fi
  VERTREFRESH="${LOWERLIMIT}-${UPPERLIMIT}"
 fi
fi

FINALDEPTH="24"
[ ! "$FINALXY" ] && FINALXY="1024x768"
[ ! "$HORIZSYNC" ] && HORIZSYNC="31-50"
[ ! "$VERTREFRESH" ] && VERTREFRESH="59-76"

echo "Section \"Screen\"
	Identifier \"Screen0\"
	Device     \"Card0\"
	Monitor    \"Monitor0\"
	DefaultDepth $FINALDEPTH
	#Option         \"metamodes\" \"PREFERREDMODE0_60 +0+0\" #METAMODES_0
	Subsection \"Display\"
		Depth       $FINALDEPTH
		Modes       \"PREFERREDMODE0\"
	EndSubsection
EndSection
" >> /tmp/xorg.conf.tmp

#fixups...
if [ "$FINALXY" = "NOTHING" ];then #130504
 sed -i -e "s/HORIZSYNC0/$HORIZSYNC/ ; s/VERTREFRESH0/$VERTREFRESH/" /tmp/xorg.conf.tmp
 sed -i -r -e 's%(.*PREFERREDMODE0.*)%#\1%' /tmp/xorg.conf.tmp #comment-out those lines.
 sed -i -e 's%PREFERREDMODE0%1024x768%' /tmp/xorg.conf.tmp #better insert a resolution.
else
 PREFERREDMODE=$FINALXY   #set monitor preferred mode same as screen mode.
 sed -i -e "s/HORIZSYNC0/$HORIZSYNC/ ; s/VERTREFRESH0/$VERTREFRESH/ ; s/PREFERREDMODE0/$PREFERREDMODE/" /tmp/xorg.conf.tmp
fi

#want a hardware profile so can bootup on different PCs...
PROFILECHIP="`grep -m1 '^oem: ' /tmp/ddcprobe.txt | cut -f 2-4 -d ' ' | tr ' ' '_' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
#'eisa:' and 'id:' return fluctuating values on some PCs, so search in this order...
PROFILEMONITOR="`grep '^monitorid: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^monitorname: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
[ "$PROFILEMONITOR" = "" ] && PROFILEMONITOR="`grep '^monitorrange: ' /tmp/ddcprobe.txt | head -n 1 | cut -f 2 -d ':' | tr -d ' ' | sed -e 's/[^0-9a-zA-Z]/_/g'`"
echo "#PuppyHardwareProfile=${PROFILECHIP}${PROFILEMONITOR}" >> /tmp/xorg.conf.tmp

if [ -f /etc/X11/xorg.conf ];then #130506
 #YMDHM="$(date +%Y-%m-%d-%H-%M)"
 YMDHM="$(stat -c %y /etc/X11/xorg.conf | cut -f 1,2 -d ':' | tr '[ :]' '-')"
 cp -f /etc/X11/xorg.conf /etc/X11/xorg.conf-BACKUP-${YMDHM} 
fi
cp -f /tmp/xorg.conf.tmp /etc/X11/xorg.conf
#create a copy of xorg.conf with the profile in the filename...
cp -af /etc/X11/xorg.conf /etc/X11/xorg.conf.${PROFILECHIP}${PROFILEMONITOR}

mv -f /root/xorg.conf.new /tmp/xorg.conf.new #130429 130503

#do we need to reboot?
REBOOT_RQD=0
case $CHOSENDRV in
 vesa)
  if [ "$ACTIVE_KMS_PTN" != "000" ];then
   #reboot is required.
   [ "$ACTIVE_KMS_i915" = "1" ] && echo 'options i915 modeset=0' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "1" ] && echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "1" ] && echo 'options radeon modeset=0' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
 modesetting)
  #don't know about this... ??????
  if [ "$KMS_all" != "111" ]; then
   [ "$ACTIVE_KMS_i915" = "0" ] && echo 'options i915 modeset=1' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "0" ] && echo 'options nouveau modeset=1' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "0" ] && echo 'options radeon modeset=1' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
 intel)
  if [ "$ACTIVE_KMS_PTN" != "100" ];then #active intel kms only
   [ "$ACTIVE_KMS_i915" = "0" ] && echo 'options i915 modeset=1' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "1" ] && echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "1" ] && echo 'options radeon modeset=0' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
 nouveau)
  if [ "$ACTIVE_KMS_PTN" != "010" ];then
   [ "$ACTIVE_KMS_i915" = "1" ] && echo 'options i915 modeset=0' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "0" ] && echo 'options nouveau modeset=1' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "1" ] && echo 'options radeon modeset=0' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
 nv)
  if [ "$ACTIVE_KMS_PTN" != "000" ];then
   [ "$ACTIVE_KMS_i915" = "1" ] && echo 'options i915 modeset=0' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "1" ] && echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "1" ] && echo 'options radeon modeset=0' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
 radeon)
  if [ "$ACTIVE_KMS_PTN" != "001" ];then
   [ "$ACTIVE_KMS_i915" = "1" ] && echo 'options i915 modeset=0' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "1" ] && echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "0" ] && echo 'options radeon modeset=1' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
 *) #all other drivers.
  if [ "$ACTIVE_KMS_PTN" != "000" ];then
   [ "$ACTIVE_KMS_i915" = "1" ] && echo 'options i915 modeset=0' > /etc/modprobe.d/i915.conf
   [ "$ACTIVE_KMS_nouveau" = "1" ] && echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf
   [ "$ACTIVE_KMS_radeon" = "1" ] && echo 'options radeon modeset=0' > /etc/modprobe.d/radeon.conf
   REBOOT_RQD=1
  fi
 ;;
esac

#150930 override the above...
case "$DISABLESECONDDRVR" in
 nouveau|nv)
  echo 'options nouveau modeset=0' > /etc/modprobe.d/nouveau.conf 
  [ "$ACTIVE_KMS_nouveau" = "1" ] && REBOOT_RQD=1
 ;;
 intel|i810)
  echo 'options i915 modeset=0' > /etc/modprobe.d/i915.conf 
  [ "$ACTIVE_KMS_i915" = "1" ] && REBOOT_RQD=1
 ;;
 radeon|r128|mach64|fglrx|ati)
  echo 'options radeon modeset=0' > /etc/modprobe.d/i915.conf
  [ "$ACTIVE_KMS_radeon" = "1" ] && REBOOT_RQD=1
 ;;
esac

echo -n "$CHOSENDRV" > /var/local/quicksetup-test-success
EX3MSG=''
if [ $REBOOT_RQD -eq 1 ];then
 dialog --title "${DLGTITLE}" --msgbox "$(eval_gettext "A reboot is required before the '\${CHOSENDRV}' driver can be tested.")

$(gettext 'Click <OK> button to reboot...')" 0 0
 #note: /root/.profile sees existence of /var/local/quicksetup-test-success and runs xorgwizard-cli instead of xwin (which starts X).
 #151210 handle frugal install...
 if [ "$PDEV1" == "zram0" ];then #frugal or live-cd
  #code from savesession...
  if [ -s /boot/initrd-tree/INSTALL_SPECS ];then #this exists if frugal install or live-cd has a saved session.
   . /boot/initrd-tree/INSTALL_SPECS #INSTALL_DEV, INSTALL_FS, INSTALL_FOLDER
   . /usr/local/install_quirky/install-funcs
   [ "${INSTALL_DEV:0:4}" == "UUID" ] && INSTALL_DEV="$(blkid | grep "\"${INSTALL_DEV:5}\"" | cut -f 1 -d ':' | cut -f 3 -d '/')" #151123
   if [ "${INSTALL_DEV:0:2}" != "sr" ];then #exclude optical.
    echo 'Saving session...'
    save_session_frugal_func #in /usr/local/install_quirky/install-funcs
    [ $? -eq 0 ] && echo '...session saved'
    exit_func 0
   fi
  fi
 fi
 sync
 exec reboot ###EXIT###
fi
#reenter this script...
exec xorgwizard-cli
###END###
