#! /bin/sh
#
# Copyright 2005 RelaxBSD All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#  1.Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#  2.Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY RelaxBSD ``AS IS'' AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of the RelaxBSD
#

export PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"

. gettext.sh

export TEXTDOMAIN=relaxconf
export TEXTDOMAINDIR='/usr/local/share/locale'

[ -f /root/.console ] && rm /root/.console

TMP="/tmp"

DIALOG="/usr/local/bin/cdialog"

if [ -x /usr/X11R6/bin/XFree86 ] ; then
    X="/usr/X11R6/bin/XFree86"
    XCONFORIG="/root/XF86Config.new"
    XCONF="/etc/X11/XF86Config-4"
elif [ -x /usr/X11R6/bin/Xorg ] ; then
    X="/usr/X11R6/bin/Xorg"
    XCONFORIG="/root/xorg.conf.new"
    XCONF="/etc/X11/xorg.conf"
else
    exit 1
fi

IS_VMWARE=`pciconf -lv | grep -i vmware`
if [ "$IS_VMWARE" ]; then
    XCONFORIG="/usr/local/share/relaxconf/`echo ${XCONF} | cut -nb 10-`.vmware"
    cp ${XCONFORIG} ${XCONF}
    exit 0
fi

[ ! -f /root/XF86Config.new -a ! -f /root/xorg.conf.new ] && $X -configure > /dev/null 2>&1

[ ! -f ${XCONFORIG} ] && exit 1

XVER=`echo $X | cut -nb "16-"`
echo "Creating ${XVER}'s configure file: $XCONFORIG"

[ "$1" = "preconfig" ] && exit 0

grep -B 2 "BoardName" $XCONFORIG > $TMP/videoTEMP.$$
VIDEOCARD="$(cat $TMP/videoTEMP.$$ | grep "VendorName" | awk -F "\"" '{print $2}')  $(cat $TMP/videoTEMP.$$ | grep "BoardName" | awk -F "\"" '{print $2}')"
rm $TMP/*TEMP*

virtual="1024x768"
depth="24"
horizsync="30-58"
refresh="50-90"
mousedev="/dev/sysmouse"

BACKTITLE=$(gettext "RelaxBSD 1.1.1 -> X configuration")
EXTRALABEL=$(gettext "Modify")
CANCELLABEL=$(gettext "Exit")
OKLABEL=$(gettext "OK")
VIRTUALHELP=$(gettext "Specifies the video modes to use.")
DEPTHHELP=$(gettext "Specifies color depth.")
HORIZSYNCHELP=$(gettext "Give the rage(s) of horizontal sync frequencies supported by the monitor.")
VERTREFRESHHELP=$(gettext "Give the rage(s) of vertical refresh frequencies supported by the monitor.")
MOUSEDEVHELP=$(gettext "Specifies the name of the driver to use for this mouse device.")
MENUTEXT=$(eval_gettext "This script will create the X initial configuration file.\n Found video card: \$VIDEOCARD")
MONITORVENDOR=`cat $XCONFORIG | grep "\"Monitor\ Vendor\""`
MONITORMODEL=`cat $XCONFORIG | grep "\"Monitor\ Model\""`

returncode=0
while test $returncode != 1 && test $returncode != 250
do
exec 3>&1
if [ -n "$MONITORVENDOR" -a -n "$MONITORMODEL" ]; then
value=`$DIALOG --clear --ok-label "${OKLABEL}" \
	--extra-label "${EXTRALABEL}" \
	--cancel-label "${CANCELLABEL}" \
	--item-help \
	--backtitle "$BACKTITLE" \
	--inputmenu "$MENUTEXT" 20 50 12 \
	"Virtual:"	"$virtual" "${VIRTUALHELP}" \
	"Depth:"	"$depth" "${DEPTHHELP}" \
	"HorizSync:" "$horizsync" "${HORIZSYNCHELP}" \
	"VertRefresh:" "$refresh" "${VERTREFRESHHELP}" \
	"Mouse device:"	"$mousedev" "${MOUSEDEVHELP}" 2>&1 1>&3`
else
value=`$DIALOG --clear --ok-label "${OKLABEL}" \
	--extra-label "${EXTRALABEL}" \
	--cancel-label "${CANCELLABEL}" \
	--item-help \
	--backtitle "$BACKTITLE" \
	--inputmenu "$MENUTEXT" 17 50 9 \
	"Virtual:"	"$virtual" "${VIRTUALHELP}" \
	"Depth:"	"$depth" "${DEPTHHELP}" \
	"Mouse device:"	"$mousedev" "${MOUSEDEVHELP}" 2>&1 1>&3`
fi
returncode=$?
exec 3>&-

	case $returncode in
	1)
		exit 1
		;;
        0)
                break
                ;;
	3)
		tag=`echo "$value" |sed -e 's/^RENAMED //' -e 's/:.*//'`
		item=`echo "$value" |sed -e 's/^.*:[ ]*//' -e 's/[ ]*$//'`
		case "$tag" in
		Virtual)
			virtual="$item"
			;;
        Depth)
			depth="$item"
			;;
        HorizSync)
            horizsync="$item"
            ;;
        VertRefresh)
            refresh="$item"
            ;;
		"Mouse device")
			mousedev="$item"
			;;
		esac
		;;
	esac
done

if echo "$mousedev" | egrep  "psm|ums|mse" > /dev/null; then
	if [ -f /var/run/moused.pid ] ;then
        MOUSEDPID=`cat /var/run/moused.pid`
		[ "`ps -p $MOUSEDPID | grep "moused"`" != "" ] && kill -INT $MOUSEDPID 2> /dev/null
		sed -e '/moused_enable/d' /etc/rc.conf > $TMP/rc.conf.$$
		mv $TMP/rc.conf.$$ /etc/rc.conf
	fi
fi

LAYOUT_DIR="/usr/X11R6/lib/X11/xkb/rules"
if [ -e $LAYOUT_DIR/xorg.lst ]; then
    LAYOUT_FILE="${LAYOUT_DIR}/xorg.lst"
else
    LAYOUT_FILE="${LAYOUT_DIR}/xfree86.lst"
fi
DIALOG_FILE="/tmp/dialTEMP.$$"
CHOOSE_FILE="/tmp/chooseTEMP.$$"

rm -f /tmp/*TEMP*

TITLE=$(gettext "RelaxBSD XFree86 Layout")
MENU=$(gettext "Choose your preferred keyboard layout")
echo "dialog --title \""${TITLE}"\" \
    --menu \""${MENU}"\" 22 50 15 \\" >> ${DIALOG_FILE}

awk '{
if ($1 == "!") {
    if ($2 == "layout") {
        getline;
        while ($0 != "!" && $0 != "") {
            print $1 "\t\"" $2 "\" \\";
            getline;
        }
     }
}
}' $LAYOUT_FILE >> ${DIALOG_FILE}
echo "2> ${CHOOSE_FILE}" >> ${DIALOG_FILE}
sh ${DIALOG_FILE}
rm -f ${DIALOG_FILE}

LAYOUT=`cat ${CHOOSE_FILE}`

sed -e 's/FontPath \"\/usr\/local\/share\/fonts\/TrueType\"//g' \
    -e '/Section \"Files\"/a \
        FontPath \"\/usr\/local\/share\/fonts\/TrueType\" \
	FontPath \"\/usr\/X11R6\/lib\/X11\/fonts\/URW\"' \
    -e '/Driver      \"kbd\"/a \
        Option  \"XkbModel\"    \"pc105\" \
        Option  \"XkbLayout\"   \"'$LAYOUT'\"' \
    -e '/\"Device\" \"\/dev\//d' \
    -e '/\"Protocol\" \"auto\"/a \
        Option  \"Device\" \"'$mousedev'\" \
        Option  \"ZAxisMapping\" \"4 5\"' \
    -e '/Monitor    \"Monitor0\"/a \
        DefaultDepth    '$depth'' \
    -e '/Depth     '$depth'/a \
            Modes     \"'$virtual'\"' \
${XCONFORIG} > ${XCONF}
if [ -n "$MONITORVENDOR" -a -n "$MONITORMODEL" ]; then
sed -e '/Section \"Monitor\"/a \
	HorizSync    '$horizsync' \
	VertRefresh  '$refresh'' ${XCONF} > /tmp/xorg.conf.orig
cp /tmp/xorg.conf.orig ${XCONF}
rm /tmp/xorg.conf.orig
fi
