#!/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
#170714 "Xorg -configure" now totally useless. replace with my own probe.
#171221 $CNT moved up.
#171231 offer fully automatic detection option.
#180311 try prevent xorgwizard running at bootup when not supposed to.
#180313 choose 'sna' or 'uxa' accel, for intel.
#180317 backup /etc/X11/xorg.conf.d with hardware profile.
#180806 xorgwizard has removed "#screen0modes" "#monitor0prefmode" needed when change res in quicksetup.
#191002 buster: have two paths, both with drivers: /usr/lib/x86_64-linux-gnu/xorg/modules/drivers /usr/lib/xorg/modules/drivers
#200113 add PuppyHardwareProfile for 'xorg.conf.d' folder.
#200114 improve PuppyHardwareProfile. see also: /usr/bin/xwin /usr/sbin/xorgwizard, xorgwizard-automatic. 200120
#200120 replace ddcprobe with /usr/sbin/get-monitor-resolutions. some rewriting.
#200121 export MONCHOICES.
#200209 renamed /etc/X11/xorg.conf.d/20-intel-* to 20-gpu-intel*

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().
mkdir -p /tmp/xorgwizard

#180313
. /etc/rc.d/WOOFMERGEVARS
case "$WOOF_VARIANT" in
 easy) PUPNAME='EasyOS' ;;
 *)    PUPNAME='Quirky' ;;
esac

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="${PUPNAME} $(gettext 'Xorg Video Wizard')" #180313

#150929 find where is xorg... ex: /usr/lib64/xorg
#191002 buster: have two paths, both with drivers: /usr/lib/x86_64-linux-gnu/xorg/modules/drivers /usr/lib/xorg/modules/drivers
# fixed in 3buildeasy distro, so only find one path here...
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

#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}"

#200120 no longer using ddcprobe to get monitor resolutions...
/usr/sbin/get-monitor-resolutions
#...this will have the native resolution of monitor: /tmp/xorgwizard/get-mon-resolution-native
#...all supported resolutions here: /tmp/xorgwizard/get-mon-resolutions
#...may have current mode: /tmp/xorgwizard/get-mon-resolution-current

##############################################################
###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
    echo "#PuppyHardwareProfile='${HARDWAREPROFILE}'" >> /tmp/xorg.conf.tmp2 #200120
    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.${HARDWAREPROFILE}
    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.${HARDWAREPROFILE}"
    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.
    [ -f /tmp/quicksetup-test-success ] && rm -f /tmp/quicksetup-test-success #180311
    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###
 if [ -s /tmp/xorgwizard/get-mon-resolutions ];then #200121
  MONCHOICES="$(cat /tmp/xorgwizard/get-mon-resolutions)" #ex: 1920 1080 60
  MONCHOICES="${MONCHOICES/ /x}"
  MONCHOICES="${MONCHOICES/ /@}" #ex: 1920x1080@60
 else
  MONCHOICES="800x600@60
1024x768@60"
 fi
 export MONCHOICES #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
   [ -f /tmp/quicksetup-test-success ] && rm -f /tmp/quicksetup-test-success #180311
   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

 rm -f /var/local/quicksetup-test-success #180311
 [ -f /tmp/quicksetup-test-success ] && rm -f /tmp/quicksetup-test-success #180311
 exit
fi

#180313
#####################################################################
###intel, choose 'sna' or 'uxa'###
if [ -s /var/local/quicksetup-test-success0 ];then #created by quicksetup
 XAUTODRV="$(cat /var/local/quicksetup-test-success0)"
 if [ "$XAUTODRV" == "intel" ];then
  if [ -f /etc/X11/xorg.conf.d/20-gpu-intel.conf ];then #200209
   CURRENTINTELACCEL="grep -o -E 'sna|uxa' /etc/X11/xorg.conf.d/20-gpu-intel.conf"
  else
   CURRENTINTELACCEL='sna'
  fi
  if [ "$CURRENTINTELACCEL" == "sna" ];then #200209
   I_msg1="$(gettext 'Currently using the \Zb\Z1intel\Zn video driver, with \Zb\Z1sna\Zn acceleration.')"
   I_msg2="$(gettext 'This may cause tearing, artifacts, or even hanging, with some video hardware. If so, click the \Zb\Z1Start X with uxa\Zn button to use the older \Zb\Z1uxa\Zn acceleration.')"
  else
   I_msg1="$(gettext 'Currently using the \Zb\Z1intel\Zn video driver, with \Zb\Z1uxa\Zn acceleration.')"
   I_msg2="$(gettext 'The \Zb\Z1sna\Zn acceleration method is the successor, best suited to relatively modern video hardware. Click the \Zb\Z1Start X with sna\Zn to use it.')"
  fi
  I_msg3="\Zb\Z1$(gettext 'Technical notes:')\Zn"
  I_msg4a="$(gettext 'You may edit the files directly:') /etc/X11/xorg.conf.d/20-intel*"
  I_msg4b="$(gettext 'In particular, note the \Zb\Z1Tear Free\Zn for sna, that may fix mild screen tearing (with some performance loss).')"
  I_msg5="$(gettext 'Choose \Zb\Z1Start X with sna\Zn or \Zb\Z1Start X with uxa\Zn. If swapping between sna and uxa brings no joy, 
choose \Zb\Z1More Fixes\Zn, or press \Zb\Z1esc\Zn key to quit the Xorg Wizard...')"
  I_yes="$(gettext 'Start X with sna')"
  I_extra="$(gettext 'Start X with uxa')"
  I_no="$(gettext 'More Fixes')"
  I_msgs="${I_msg1}
${I_msg2}

${I_msg3}
${I_msg4a}
${I_msg4b}

${I_msg5}"
  dialog --colors --extra-button --ok-label "${I_yes}" --cancel-label "${I_no}" --extra-label "${I_extra}" --title "${DLGTITLE}" --yesno "${I_msgs}" 0 0
  case $? in
   0) #ok/yes -- sna
    [ -f /etc/X11/xorg.conf.d/20-gpu-intel.confSNA ] && cp -f /etc/X11/xorg.conf.d/20-gpu-intel.confSNA /etc/X11/xorg.conf.d/20-gpu-intel.conf
    #180317 backup with hardware profile...
    [ -d /etc/X11/xorg.conf.d.${HARDWAREPROFILE} ] && rm -rf /etc/X11/xorg.conf.d.${HARDWAREPROFILE}
    cp -a /etc/X11/xorg.conf.d /etc/X11/xorg.conf.d.${HARDWAREPROFILE}
    echo 'Starting X with sna acceleration'
    exec xwin
   ;;
   3) #extra -- uxa (this button displays between ok and cancel buttons)
    [ -f /etc/X11/xorg.conf.d/20-gpu-intel.confUXA ] && cp -f /etc/X11/xorg.conf.d/20-gpu-intel.confUXA /etc/X11/xorg.conf.d/20-gpu-intel.conf
    #180317 backup with hardware profile...
    [ -d /etc/X11/xorg.conf.d.${HARDWAREPROFILE} ] && rm -rf /etc/X11/xorg.conf.d.${HARDWAREPROFILE}
    cp -a /etc/X11/xorg.conf.d /etc/X11/xorg.conf.d.${HARDWAREPROFILE}
    echo 'Starting X with uxa acceleration'
    exec xwin
   ;;
   1) #cancel/no -- more fixes
    true
   ;;
   *) #quit
    echo 'Have done nothing, exited Xorg Wizard.'
    exit
   ;;
  esac
 fi
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

#170714 does not get them all...
#GPUDRM_MODS="$(ls ${GPUDRM_PATH}/*/*.ko | rev | cut -f 1 -d '/' | cut -f 2 -d '.' | rev)" #list all gpu drm modules.
GPUDRM_MODS="$(find ${GPUDRM_PATH} -mindepth 2 -type f -name '*.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}"

############
#start with a skeleton xorg.conf...
cp -f /etc/X11/xorg.conf0 /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

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

#170714 instead, from loaded kernel gpu driver(s), select what xorg drivers to use...
DRVPARAMS=''
DRVPARAMS_NOUVEAU='    #ref: http://manpages.ubuntu.com/manpages/xenial/man4/nouveau.4.html
    #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>]'
DRVPARAMS_NV='    #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>]'
DRVPARAMS_INTEL='    #ref: http://manpages.ubuntu.com/manpages/xenial/man4/intel.4.html
    #Option     "NoAccel"               # [<bool>]
    #Option     "AccelMethod"           # <str>
    #Option     "Backlight"             # <str>
    #Option     "DRI"                   # [<bool>]
    #Option     "ColorKey"              # <i>
    #Option     "VideoKey"              # <i>
    #Option     "Tiling"                # [<bool>]
    #Option     "LinearFramebuffer"     # [<bool>]
    #Option     "SwapbuffersWait"       # [<bool>]
    #Option     "XvPreferOverlay"       # [<bool>]
    #Option     "HotPlug"               # [<bool>]
    #Option     "RelaxedFencing"        # [<bool>]
    #Option     "XvMC"                  # [<bool>]
    #Option     "Throttle"              # [<bool>]
    #Option     "ZaphodHeads"           # <str>
    #Option     "DelayedFlush"          # [<bool>]
    #Option     "TearFree"              # [<bool>]
    #Option     "PerCrtcPixmaps"        # [<bool>]
    #Option     "FallbackDebug"         # [<bool>]
    #Option     "DebugFlushBatches"     # [<bool>]
    #Option     "DebugFlushCaches"      # [<bool>]
    #Option     "DebugWait"             # [<bool>]
    #Option     "BufferCache"           # [<bool>]
    #Option     "TripleBuffer"          # [<bool>]'
DRVPARAMS_FBDEV='    #Option     "ShadowFB"              # [<bool>]
    #Option     "Rotate"                # <str>
    #Option     "fbdev"                 # <str>
    #Option     "debug"                 # [<bool>]'
DRVPARAMS_RADEON='    #ref: http://manpages.ubuntu.com/manpages/xenial/man4/radeon.4.html
    #Option "SWcursor" "boolean"
    #Option "Accel" "boolean"
    #Option "ZaphodHeads" "string"
    #Option "ColorTiling" "boolean"
    #Option "ColorTiling2D" "boolean"
    #Option "DRI" "integer"
    #Option "EnablePageFlip" "boolean"
    #Option "TearFree" "boolean"
    #Option "AccelMethod" "string"'
DRVPARAMS_AMDGPU='    #ref: http://manpages.ubuntu.com/manpages/xenial/man4/amdgpu.4.html
    #Option "SWcursor" "boolean"
    #Option "Accel" "boolean"
    #Option "ZaphodHeads" "string"
    #Option "DRI" "integer"
    #Option "EnablePageFlip" "boolean"
    #Option "TearFree" "boolean"
    #Option "AccelMethod" "string"
    #Option "ShadowPrimary" "boolean"'

CNT=0
echo -n '' > /root/xorg.conf.new
for aKERNELGPU in $GPUDRM_LOADED_MODS
do
 [ "$aKERNELGPU" == "" ] && continue
 #on left are kernel modules, on right are xorg driver(s)...
 case $aKERNELGPU in
  radeon)  XORGDRVS='radeon' ;;
  amdgpu)  XORGDRVS='amdgpu' ;;
  ttm)     XORGDRVS='' ;;
  udl)     XORGDRVS='' ;;
  i915)    XORGDRVS='intel' ;;
  nouveau) XORGDRVS='nouveau nv' ;;
  tda998x) XORGDRVS='' ;;
  sil164)  XORGDRVS='' ;;
  ch7006)  XORGDRVS='' ;;
  gma500_gfx) XORGDRVS='' ;;
  *) XORGDRVS='' ;;
 esac
 for aXORGDRV in $XORGDRVS
 do
  [ ! -f ${XORGPATH}/modules/drivers/${aXORGDRV}_drv.so ] && continue
  DRVPARAMS='    #'
  case $aXORGDRV in
   nouveau) DRVPARAMS="$DRVPARAMS_NOUVEAU" ;;
   nv)      DRVPARAMS="$DRVPARAMS_NV" ;;
   intel)   DRVPARAMS="$DRVPARAMS_INTEL" ;;
   radeon)   DRVPARAMS="$DRVPARAMS_RADEON" ;;
   amdgpu)   DRVPARAMS="$DRVPARAMS_AMDGPU" ;;
  esac
  echo "
Section \"Device\"
	Identifier  \"Card${CNT}\"
${DRVPARAMS}
	Driver      \"${aXORGDRV}\"
EndSection" >> /root/xorg.conf.new
  CNT=`expr $CNT + 1` #171221 moved up.
 done
done
#170714 if xorg previously used a xorg driver, add it...
if [ -s /var/local/quicksetup-test-success0 ];then #created in quicksetup.
 XAUTODRV="`cat /var/local/quicksetup-test-success0`"
 if [ -f ${XORGPATH}/modules/drivers/${XAUTODRV}_drv.so ];then
  autoPTN="Driver *\"${XAUTODRV}\""
  if [ "$(grep "$autoPTN" /root/xorg.conf.new)" = "" ];then
   echo "
Section \"Device\"
	Identifier  \"Card${CNT}\"
	Driver      \"${XAUTODRV}\"
EndSection" >> /root/xorg.conf.new
  fi
 fi
fi



#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###
#170714 remove...
#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 "
Section \"Monitor\"
	Identifier   \"Monitor0\"
	#HorizSync    HORIZSYNC0
	VertRefresh  VERTREFRESH0
	#UseModes     \"Modes0\" #monitor0usemodes
	Option      \"PreferredMode\" \"PREFERREDMODE0\" #monitor0prefmode
EndSection" >> /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
DRIVERLIST0="$(sort --key=2,2 --unique /tmp/xorgwizard-driverlist0 | cut -f 2- -d ' ' | tr '\n' ' ')"

#171231 restore fully automatic detection
DRIVERLIST="${DRIVERLIST0} -none- \"Fully automatic detection\""

#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

#171231 fully auto
if [ "$CHOSENDRV" == "-none-" ];then
echo "
$(gettext 'Fully automatic detection, deleting /etc/X11/xorg.conf, and executing /usr/sbin/xorgwizard-automatic...')"
 [ -f /etc/X11/xorg.conf ] && mv -f /etc/X11/xorg.conf /etc/X11/xorg.confBAK1
 rm -f /root/.XLOADED 2> /dev/null #not necessary, precaution.
 /usr/sbin/xorgwizard-automatic
 exit
fi

#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=""

if [ -s /tmp/xorgwizard/get-mon-resolutions ];then #from /usr/sbin/get-monitor-resolutions
 XYRESS="$(cut -f 1,2 -d ' ' /tmp/xorgwizard/get-mon-resolutions | tr ' ' 'x')"
else
 XYRESS="800x600
1024x768
1280x1024"
fi
NATIVE_RES=''
echo -n '' > /tmp/xorgwizard/xychoices
if [ -s /tmp/xorgwizard/get-mon-resolution-native ];then #ex: 1920 1080 60
 NATIVE_RES="$(cat /tmp/xorgwizard/get-mon-resolution-native | tr ' ' 'x' | cut -f 1,2 -d 'x')"
fi
for aRES in $XYRESS
do
 [ ! "$aRES" ] && continue
 if [ "$aRES" == "$NATIVE_RES" ];then
  aTXT="Monitor native resolution"
 else
  case "$aRES" in
   640x480|800x600|1024x768|1280x1024)
    aTXT="VESA standard resolution"
   ;;
   1366x768|1920x1080|1280x720)
    aTXT="Wide-screen resolution"
   ;;
   3840x2160|4096x2160)
    aTXT="4K wide-screen resolution"
   ;;
   *)
    aTXT=""
   ;;
  esac
 fi
 echo "${aRES} \"${aTXT}\"" >> /tmp/xorgwizard/xychoices
done
XYCHOICES="$(cat /tmp/xorgwizard/xychoices | 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

#200120 replace ddcprobe to get monitor freq:
if [ -s /tmp/xorgwizard/get-mon-edid ];then #see /usr/sbin/get-monitor-resolutions
 HORIZSYNC="$(cat /tmp/xorgwizard/get-mon-edid | tr '\t' ' ' | tr -d ' ' | grep -i '^Horizsync[0-9]' | sed -e 's%[a-zA-Z]*%%')"
 VERTREFRESH="$(cat /tmp/xorgwizard/get-mon-edid | tr '\t' ' ' | tr -d ' ' | grep -i '^VertRefresh[0-9]' | sed -e 's%[a-zA-Z]*%%')"
 #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\" #screen0modes
	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...
echo "#PuppyHardwareProfile='${HARDWAREPROFILE}'" >> /tmp/xorg.conf.tmp #200120

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.${HARDWAREPROFILE}
echo "PuppyHardwareProfile='${HARDWAREPROFILE}'" > /etc/X11/xorg.conf.d/PuppyHardwareProfile #200113
[ -d /etc/X11/xorg.conf.d.${HARDWAREPROFILE} ] && rm -rf /etc/X11/xorg.conf.d.${HARDWAREPROFILE} #200113
cp -a /etc/X11/xorg.conf.d /etc/X11/xorg.conf.d.${HARDWAREPROFILE} #200113

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