#!/bin/sh
# (C) 2006 por Marcos Guglielmetti
# Bajo licencia GNU GPL v2 o posterior
# Under GNU GPL v2 or later
# 
# Script: xorgmusix.sh
# Versión 0.2
# Provides: a good xorg.conf file? ;)
#
# Objetivo: lograr una buena detección de hardware de video
# dado que los scripts actualmente presentes en la
# mayoría de las distros no logran aprovechar 
# los recursos de todo el hardware de video, incluso
# en Musix o Knoppix el monitor en general no es bien
# detectado o no es detectado en absoluto
# 
# Y la aceleración 3D casi nunca es habilitada, por lo cual
# no se puede jugar videogames y tabién influye en 
# los programas de audio que usan JACK porque el procesador
# se encuentra realizando tareas para el video que debería
# realizar la misma placa de video.
#
#



# creamos directorio temp si no existe
[ -d /etc/X11/temp ] || mkdir /etc/X11/temp

cp /etc/X11/xorg.conf /etc/X11/temp/xorg.conf.orig

XCONFORIG="/etc/X11/temp/xorg.conf.orig"
TEMPDIR="/etc/X11/temp/"

export USAR_NLS=si
export TEXTDOMAIN=xorgmusix
export TEXTDOMAINDIR="/etc/musix/locales"

#Contenido de config/encabezado :

. /etc/musix/funciones-i18n
[ -e /etc/musix/funciones ] && . /etc/musix/funciones
#Fin de config/encabezado
#Fin de las modificaciones.
# Funciones: Copyright 2005 Adrian Pardini
# Released under GNU GPL
#i18n y algunos bugfixes.
#puede ser -nearmouse o -center (o nada)
pos="-nearmouse"
probar_X && x=1
if [ -z $USER ]; then export USER=root; fi
if [ -z $HOME ]; then export HOME=/root; fi
if [ "$HOME" = "/" ]; then export HOME=/root; fi

if [ $x ]
then
echo "Error: Estamos en X, no podemos operar así, 
debes ejecutar este script fuera del escritorio, 
en una terminal de texto.

Para acceder a una, sal del escritorio... puedes
presionar control+alt+f1, entrar como root, matar
X con killall X o killall Xorg y luego volver
a ejecutar este script escribiendo xorgmusix.sh

Error: we are in a desktop environment,
this script only works into a text console.

Press: control+alt+f1
enter as root user
killall X
or killall Xorg

And type: xorgmusix.sh


" | gmessage -wrap -title "Musix GNU+Linux" -file - $pos -geometry 360x430

#exit 1 ### debug
else
echo "Musix's Xorg configuration method, working..."
fi
	

# Planificando qué secciones debe tener un archivo xorg.conf

#Section "ServerLayout" (se definen mouse, teclado, screen)
#Section "ServerFlags" (algunas opciones de inicio extras)
#Section "extensions" (para utilizar extensiones, como composite)
#Section "Files" (RgbPath, FontPath, ModulePath y  )
#Section "Module" (carga de módulos, ej.: ddc, dri, GLcore)
#Section "InputDevice" (Keyboard)
#Section "InputDevice" (Identifier  "Serial Mouse")
#Section "InputDevice"	(Identifier  "PS/2 Mouse")
#Section "InputDevice" (Identifier      "USB Mouse")
# ### : Xorg -configure detecta bien esto:
#Section "Monitor" ("Monitor0", esto lo detecta Xorg -configure)
#Section "Device" (Available Driver options para la placa de video y el driver en sí van aquí, ej.: Driver      "savage")
# ###
#Section "Screen" (diferentes modos de video para este hard.)
#Section "DRI"	(Mode 0666)



dividir () {
# ESTA es una función que divide en dos el archivo
# xorg.conf para poder operar bien: busca un string
# y que divide en dos partes desde allí
# NOTE: esto sólo siver si queremos insertar una o más líneas
# en un lugar, no sive para editar una sección entera.
#
# Devuelve 2 archivos xorg.conf antes y después del string
# pasado ($1)


echo "Trabajando sobre $XCONFORIG"
sleep 1s

TOTAL_LINEAS=`cat $XCONFORIG | wc -l`

echo "Total de líneas en $XCONFORIG: $TOTAL_LINEAS"

# averiguando línea de central
LINEACENTRAL=`cat $XCONFORIG | grep -n "$1" | cut -f1 -d":"`

echo "la línea central de división es: $LINEACENTRAL"

# para la parte 2
TAIL=`expr $TOTAL_LINEAS - $LINEACENTRAL`

echo "el tail es $TAIL"

# creamos el archivo dividido, parte1
cat $XCONFORIG | head -$LINEACENTRAL > $TEMPDIR/xorg.conf_part1

# creamos el archivo dividido, parte2
cat $XCONFORIG | tail -$TAIL > $TEMPDIR/xorg.conf_part2

}

# TODO: para dividir secciones podríamos hacer un
# while: hasta que no encuentre EndSection no frena
# y va contando las líneas...


# probando la función
dividir "Section \"Screen\""


# Bien, planifiquemos el script
# TIENE QUE:
# 1) partir de un template general, en el cual estarían las secciones
# predefinidas genéricas: mouse y teclado, y estas:

# ### template parte 1:
#Section "ServerLayout" (se definen mouse, teclado, screen)
#Section "ServerFlags" (algunas opciones de inicio extras)
#Section "extensions" (para utilizar extensiones, como composite)
#Section "Files" (RgbPath, FontPath, ModulePath y  )
#Section "Module" (carga de módulos, ej.: ddc, dri, GLcore)
#Section "InputDevice" (Keyboard)
#Section "InputDevice" (Identifier  "Serial Mouse")
#Section "InputDevice"	(Identifier  "PS/2 Mouse")
#Section "InputDevice" (Identifier      "USB Mouse")
# ### fin template parte1
#
# ### insersión de lo detectado por Xorg -configure
#
# ### template parte 2:
#Section "Screen" (diferentes modos de video para este hard.)
#Section "DRI"	(Mode 0666)
# ### fin total

# Y estas serían las que tomamos del Xorg -configure:
#Section "Monitor" ("Monitor0", esto lo detecta Xorg -configure)
#Section "Device" (Available Driver options para la placa de video
# y el driver en sí van aquí, ej.: Driver      "savage")


# definiendo templates genéricos para todos los casos.
TEMPLATE1="
# /etc/X11/xorg.conf, created by xorgmusix.sh\n
\n
Section \"ServerLayout\"\n
    Identifier     \"Xorg Configurado\"\n
    Screen      0  \"Screen0\" 0 0\n
    InputDevice    \"Keyboard0\" \"CoreKeyboard\"\n
    InputDevice    \"Serial Mouse\" \"CorePointer\"\n
    # habilitamos esto?\n
    #InputDevice    \"PS/2 Mouse\" \"CorePointer\"\n
    InputDevice    \"USB Mouse\" \"CorePointer\"\n
EndSection\n
\n
Section \"ServerFlags\"\n
    Option \"AllowMouseOpenFail\"  \"true\"\n
EndSection\n
\n
##disabled## Section \"extensions\"\n
    ##disabled## Option \"Composite\"  \"Enable\"\n
    ##disabled## Option \"RENDER\"  \"Enable\"\n
##disabled## EndSection\n
\n
Section \"Files\"\n
	RgbPath      \"/usr/X11R6/lib/X11/rgb\"\n
	#ModulePath   \"/usr/X11R6/lib/modules\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/misc:unscaled\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/misc\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/75dpi:unscaled\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/75dpi\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/100dpi:unscaled\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/100dpi\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/Speedo\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/PEX\"\n
# Additional fonts: Locale, Gimp, TTF...\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/cyrillic\"\n
#	FontPath     \"/usr/X11R6/lib/X11/fonts/latin2/75dpi\"\n
#	FontPath     \"/usr/X11R6/lib/X11/fonts/latin2/100dpi\"\n
# True type and type1 fonts are also handled via xftlib, see /etc/X11/XftConfig!\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/Type1\"\n
	FontPath     \"/usr/share/fonts/ttf/western\"\n
	FontPath     \"/usr/share/fonts/ttf/decoratives\"\n
	FontPath     \"/usr/share/fonts/truetype\"\n
	FontPath     \"/usr/share/fonts/truetype/openoffice\"\n
	FontPath     \"/usr/share/fonts/truetype/ttf-bitstream-vera\"\n
	FontPath     \"/usr/share/fonts/latex-ttf-fonts\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/defoma/CID\"\n
	FontPath     \"/usr/X11R6/lib/X11/fonts/defoma/TrueType\"\n
EndSection\n
\n
Section \"Module\"\n
        Load  \"ddc\"  # ddc probing of monitor\n
	Load  \"GLcore\"\n
	Load  \"dbe\"\n
	Load  \"dri\"\n
	Load  \"extmod\"\n
	Load  \"glx\"\n
        Load  \"bitmap\" # bitmap-fonts\n
	Load  \"speedo\"\n
	Load  \"type1\"\n
	Load  \"freetype\"\n
	Load  \"record\"\n
EndSection\n
\n
Section \"InputDevice\"\n
	Identifier  \"Keyboard0\"\n
	Driver      \"keyboard\"\n
        Option      \"CoreKeyboard\"\n
	Option \"XkbRules\" \"xorg\"\n
	Option \"XkbModel\" \"pc105\"\n
EndSection\n
\n
Section \"InputDevice\"\n
	Identifier  \"Serial Mouse\"\n
	Driver      \"mouse\"\n
	Option      \"Protocol\" \"Microsoft\"\n
	Option      \"Device\" \"/dev/ttyS0\"\n
	Option      \"Emulate3Buttons\" \"true\"\n
	Option      \"Emulate3Timeout\" \"70\"\n
	Option	    \"SendCoreEvents\"  \"true\"\n
	# mouse wheel, rueda del mouse\n
	#Option \"ZAxisMapping\" \"4 5\"\n
EndSection\n
\n
Section \"InputDevice\"\n
	Identifier  \"PS/2 Mouse\"\n
	Driver      \"mouse\"\n
	Option      \"Protocol\" \"auto\"\n
Option          \"ZAxisMapping\"          \"4 5\"\n
	Option      \"Device\" \"/dev/psaux\"\n
	Option      \"Emulate3Buttons\" \"true\"\n
	Option      \"Emulate3Timeout\" \"70\"\n
	Option	    \"SendCoreEvents\"  \"true\"\n
EndSection\n
\n
Section \"InputDevice\"\n
        Identifier      \"USB Mouse\"\n
        Driver          \"mouse\"\n
        Option          \"Device\"                \"/dev/input/mice\"\n
	Option		\"SendCoreEvents\"	\"true\"\n
        Option          \"Protocol\"              \"IMPS/2\"\n
        Option          \"ZAxisMapping\"          \"4 5\"\n
        Option          \"Buttons\"               \"5\"\n
EndSection\n
\n
"

TEMPLATE2="\n
Section \"Screen\"\n
	Identifier \"Screen0\"\n
	Device     \"Card0\"\n
	Monitor    \"Monitor0\"\n
	DefaultColorDepth 16\n
	SubSection \"Display\"\n
		Depth     1\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
	SubSection \"Display\"\n
		Depth     4\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
	SubSection \"Display\"\n
		Depth     8\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
	SubSection \"Display\"\n
		Depth     15\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
	SubSection \"Display\"\n
		Depth     16\n
	# You can add things links \"1280x768\" here...\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
	SubSection \"Display\"\n
		Depth     24\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
	SubSection \"Display\"\n
		Depth     32\n
		Modes \"1024x768\" \"800x600\" \"640x480\"\n
	EndSubSection\n
EndSection\n
\n
Section \"DRI\"\n
	Mode 0666\n
EndSection\n
\n
"


# Es decir que tenemos que separar las dos secciones del archivo
# obtenido por Xorg -configure
#
# 1: "Section \"Monitor\""
# 2: Section "Device"

# Es fácil entontrar el principio de la sección, pero el final
# requerirá de un while sumando líneas en una variable... 
# bien, veremos...


# Obtenemos el archivo nuevo
XORG_CONFIGURE="/root/xorg.conf.new"
Xorg -configure
if [ "$?" = "0" ]
then
echo "Archivo de detección de hardware de video
creado correctamente en: $XORG_CONFIGURE"
else
echo "ERROR: el archivo de detección de hardware de video
no pudo ser creado, X está corriendo?, saliendo..."
# ### exit 1 ### debug... no salgo...
fi



# Creando las secciones Monitor y Device

echo "Trabajando sobre $XORG_CONFIGURE
Creando las secciones Monitor y Device"
sleep 1s ## debug

echo "Comenzamos por Monitor:"
TOTAL_LINEAS=`cat $XORG_CONFIGURE | wc -l`
echo "Total de líneas en $XORG_CONFIGURE: $TOTAL_LINEAS"
# averiguando línea de central

# mientras la línea no diga "EndSection", vamos creando
# las líneas de esa sección...

# Esto era más sencillo de lo pensado: teóricamente
# el Xorg -configure crea siempre 8 secciones, y con un
# | grep -n Section | grep -v Sub
#1:Section "ServerLayout"
#6:EndSection
#8:Section "Files"
#18:EndSection
#20:Section "Module"
#29:EndSection
#31:Section "InputDevice"
#34:EndSection
#36:Section "InputDevice"
#42:EndSection
#44:Section "Monitor"
#53:EndSection
#55:Section "Device"
#90:EndSection
#92:Section "Screen"
#120:EndSection

# Es decir que para saber donde empieza y comienza la
# del monitor es con esto: | grep -n Section | grep -v Sub | head -12 | tail -2
# siempre y cuando el archivo tenga 8 secciones...

MONITOR_START=`cat $XORG_CONFIGURE | grep -n Section | grep -v Sub | head -12 | tail -2 | head -1 | cut -f1 -d":"`
#
echo "Línea de comienzo de la sección Monitor: $MONITOR_START"

MONITOR_END=`cat $XORG_CONFIGURE | grep -n Section | grep -v Sub | head -12 | tail -2 | tail -1 | cut -f1 -d":"`
#
echo "Línea EndSection de la sección Monitor: $MONITOR_END"

# para hacer el tail hay que: restar a las líneas totales
# el número de línea de comienzo + 1

TAIL_M_START=`expr $TOTAL_LINEAS - $MONITOR_START + 1`
# para hacer el head, es necesario restar Monitor_start - monitor_end + 1
HEAD_M_END=`expr $MONITOR_END - $MONITOR_START + 1`

cat $XORG_CONFIGURE | tail -$TAIL_M_START | head -$HEAD_M_END > $TEMPDIR/SectionMonitor

echo "La sección para el monitor es:"
cat $TEMPDIR/SectionMonitor



# ### device:

echo "Section Device"
TOTAL_LINEAS=`cat $XORG_CONFIGURE | wc -l`
echo "Total de líneas en $XORG_CONFIGURE: $TOTAL_LINEAS"
# averiguando línea de central

# mientras la línea no diga "EndSection", vamos creando
# las líneas de esa sección...

# Esto era más sencillo de lo pensado: teóricamente
# el Xorg -configure crea siempre 8 secciones, y con un
# | grep -n Section | grep -v Sub
#1:Section "ServerLayout"
#6:EndSection
#8:Section "Files"
#18:EndSection
#20:Section "Module"
#29:EndSection
#31:Section "InputDevice"
#34:EndSection
#36:Section "InputDevice"
#42:EndSection
#44:Section "Monitor"
#53:EndSection
#55:Section "Device"
#90:EndSection
#92:Section "Screen"
#120:EndSection

# Es decir que para saber donde empieza y comienza la
# del monitor es con esto: | grep -n Section | grep -v Sub | head -12 | tail -2
# siempre y cuando el archivo tenga 8 secciones...

DEVICE_START=`cat $XORG_CONFIGURE | grep -n Section | grep -v Sub | head -14 | tail -2 | head -1 | cut -f1 -d":"`
#
echo "Línea de comienzo de la sección DEVICE: $DEVICE_START"

DEVICE_END=`cat $XORG_CONFIGURE | grep -n Section | grep -v Sub | head -14 | tail -2 | tail -1 | cut -f1 -d":"`
#
echo "Línea EndSection de la sección DEVICE: $DEVICE_END"

# para hacer el tail hay que: restar a las líneas totales
# el número de línea de comienzo + 1

TAIL_M_START=`expr $TOTAL_LINEAS - $DEVICE_START + 1`
# para hacer el head, es necesario restar DEVICE_start - DEVICE_end + 1
HEAD_M_END=`expr $DEVICE_END - $DEVICE_START + 1`

cat $XORG_CONFIGURE | tail -$TAIL_M_START | head -$HEAD_M_END > $TEMPDIR/SectionDEVICE

echo "La sección para el DEVICE es:"
cat $TEMPDIR/SectionDEVICE


# ### Creando xorg.conf final ###
# Haciendo backup del anterior

if [ -f /etc/X11/xorg.conf.bak.xorgmusix ]
then
echo "El backup del archivo de configuración de xorg
 anterior ya existe, sobreescribiendo
/etc/X11/xorg.conf.bak.xorgmusix"
cp -v /etc/X11/xorg.conf /etc/X11/xorg.conf.bak.xorgmusix
else
echo "Creando backup del archivo xorg.conf anterior:
/etc/X11/xorg.conf.bak.xorgmusix"
cp -v /etc/X11/xorg.conf /etc/X11/xorg.conf.bak.xorgmusix
sleep 2s
fi


# Creando el xorg.conf final
echo -n -e $TEMPLATE1 > /etc/X11/xorg.conf
cat $TEMPDIR/SectionMonitor >> /etc/X11/xorg.conf
cat $TEMPDIR/SectionDEVICE >> /etc/X11/xorg.conf
echo -n -e $TEMPLATE2 >> /etc/X11/xorg.conf

echo "Creación del archivo xorg.conf terminada con exito!"
sleep 1s

# movemos el archivo temporal a un lugar mejor...
mv /root/xorg.conf.new /tmp/

if [ -f /root/Desktop/Autostart/krandrtray ]
then
echo "krandrtray en escritorio root iniciará automáticamente"
else
echo "Creando link para autoinicio de krandrtray en escritorio root"
ln -s /usr/bin/krandrtray /root/Desktop/Autostart/krandrtray
fi