#!/bin/bash
# videoconfig.sh
# Versión 0.2
# Copyright 2006 Marcos Guglielmetti 
# Released under GNU GPL 2 or later
#
# Utilidad gráfica para configurar el modo en que Musix
# detecta el video. Además se puede editar xorg.conf
# y tiene funciones para cambiar resolución de video
#
# TODO: diseñar un método de reinicio de X mejor
# * copiar el método de reinicio de X de puppy
#
# TODO: falta hacerlo funcionar con dialog desde consola y con kdialog 
# en X

# Nuevo en Musix 0.59, porque sino puede fallar
# si no existen estas variables, las creamos.
[ -z $HOME ] && HOME=/root
[ -z $USER ] && USER=root



echo "debug!1"

KERNEL=`uname -r`

# esto es por Musix
export USAR_NLS=si
export TEXTDOMAIN=videoconfig
export TEXTDOMAINDIR="/etc/musix/locales"


# Esto es para internacionalización dentro de Musix
# No está implementado en este script aún... TODO

#Contenido de config/encabezado :
. /etc/musix/funciones-i18n
[ -e /etc/musix/funciones ] && . /etc/musix/funciones

## Fin locales



# Si ya está instalado, avisa y pregunta si quiere instalar nuevos programas con synaptic
INSTALLED="no"
[ -e /KNOPPIX/bin/ash ] || INSTALLED="yes"
if [ "$INSTALLED" = "yes" ]
then

echo "Musix está instalado en HD"

else


	lsmod | grep unionfs
	if [ "$?" = "1" ]
	then
	echo "no UNIONFS: Musix No está instalado en HD... 
	si el kernel no soporta	unionfs, este script 
	no funcionará bien..."

	# we are guessing that unionfs is not loaded (TODO: try with lsmod instead)
	echo "Not an UNIONFS filesystem, so..."
	gmessage "Estamos corriendo desde el kernel $KERNEL
	sin capacidad para modificar ciertos archivos de configuración,
	entre los que se incluyen los de video... por lo tanto
	este script no funcionará normalmente.
	Inicia con el kernel estandard para mayor funcionalidad en 
	este sentido.
	
	We are running a $KERNEL kernel without unionfs filesystem
	so this videoconfig script will not run normally.
	Start from the standard kernel for better functionality 
	into this issue.
	"
	
	fi


fi


##OK

# Sólo corremos si somos root (tomado de Knoppix installer )
if [ $UID -eq 0 ];
then
  echo "Ok, root user..."
else
  echo "Se necesitan privilegios de root. / root permission needed."
  gmessage "Se necesitan privilegios de root. / root permission needed."
fi




# si no existen estos archivos, no podemos continuar...
[ -f /usr/sbin/mkxf86config-musix ] || exit 1
[ -f /usr/sbin/mkxf86config-gentoo ] || exit 1

AUTODETECT="no"
# ver si está habilitada la autodetección:
[ -f /usr/sbin/mkxf86config ] && AUTODETECT="yes"
[ -f /usr/sbin/mkxf86config ] || AUTODETECTM="-"

# Ver en qué método está
ls -lah /usr/sbin/mkxf86config | grep musix && AUTODETECTM="musix knoppix"
ls -lah /usr/sbin/mkxf86config | grep xorgmusix && AUTODETECTM="Musix's new method"
ls -lah /usr/sbin/mkxf86config | grep gentoo && AUTODETECTM="gentoo"


XCONFIG="/etc/X11/xorg.conf"
# backup reciente:
cp $XCONFIG /etc/X11/xorg.conf.bak
# Hace backup una sola vez
[ -f /etc/X11/xorg.conf.bak2 ] || cp $XCONFIG /etc/X11/xorg.conf.bak2
# Info: este comando deja el nombre del archivo sin extensión, para luego
# poder tratarlo como MIDI
#ls $1 | cut -f1 -d"."


# Comenzamos...

# Buscamos xmessage o gmessage y usamos el mejor...
[ -f /usr/X11R6/bin/xmessage ] && MESSAGE="xmessage" && echo "existe xmessage"
[ -f /usr/bin/gmessage ] && MESSAGE="gmessage" && echo "existe gmessage"


# Buscamos y elegimos el editor de textos _liviano_ comenzando por el más pesado, y por los menos recomendables
# esto lo hacemos para que el script funcione en otras distros
[ -f /usr/bin/emacs ] && TEXTED="xterm -e emacs" && echo "existe emacs"
[ -f /usr/bin/vim ] && TEXTED="xterm -e vim" && echo "existe vim"
[ -f /usr/bin/nano ] && TEXTED="xterm -e nano" && echo "existe nano"
[ -f /usr/bin/gvim ] && TEXTED="gvim" && echo "existe gvim"
[ -f /usr/bin/kedit ] && TEXTED="kedit" && echo "existe kedit"
[ -f /usr/bin/leafpad ] && TEXTED="leafpad" && echo "existe leafpad"

# Buscamos y elegimos el navegador
[ -f /usr/bin/firefox ] && BROWSER="firefox" && echo "existe firefox"
[ -f /usr/bin/nautilus ] && BROWSER="nautilus" && echo "existe nautilus"
[ -f /usr/bin/dillo ] && BROWSER="dillo" && echo "existe dillo"
[ -f /usr/bin/konqueror ] && BROWSER="konqueror" && echo "existe konqueror"

# Buscamos y elegimos el _mejor_ secuenciador MIDI
# Noteedir no puede abrir archivos midi en un principio... por ahora...
#[ -f /usr/bin/noteedit ] && SEQ="noteedit" && echo "existe noteedit"
[ -f /usr/bin/muse ] && SEQ="muse" && echo "existe muse"
[ -f /usr/bin/rosegarden ] && SEQ="rosegarden" && echo "existe rosegarden"


# Existe el manual?
[ -f /usr/doc/musix/ayuda.html ] && MANUALES="/usr/doc/musix/ayuda.html" && echo "existe el manual en español"
[ -f /usr/doc/musix/index.html ] && MANUALINDEX="/usr/doc/musix/index.html" && echo "existe el manual en varios idiomas"



# NOTE: kcmshell --nocrashhandler xserver devuelve información clara sobre el video...

# # #

# Aquí debemos definir la función, que luego será llama más tarde, en lugar de llamarse el script a sí mismo como hacía en la versión 0.31

# to configure from a text console
configconsola () {

EXIT="no"
while [ $EXIT="no" ]
do

TEXTED="nano"
BROWSER="elinks"



sleep 1s
dialog --backtitle "Musix $MUSIXVERSION" \
    --menu "Select" 0 0 0 \
    "0" " Enable autodetection method 0: Musix's new"\
    "1" " Enable autodetection method 1: Musix Knoppix's"\
    "2" " Enable autodetection method 2: Gentoo's live-cd"\
    "3" " Disable video autodetection / Desabilitar autodetección de video"\
    "4" " Restart X to test your changes / Reiniciar X para probar los cambios"\
    "5" " Restore X config / Restaurar configuración de X"\
    "6" " Help docs / Ayuda"\
    "7" " /etc/X11/xorg.conf manual edit"\
    "8" " Forece X resolution to 800x600"\
    "9" " Set X resolution to 1024x768"\
    "10" " Reconfigure Xorg (advanced users)"\
    "11" " Exit / Salir " 2> /tmp/menu

# este metodo de cancelar no funciona...
#[ -f /tmp/menu ] || exit

[ -f /tmp/menu ] && RESULTADO=`cat /tmp/menu`

	if [ "$RESULTADO" = "11" ]
	then
	EXIT="yes"
	export $EXIT
	exit 0
	fi

	if [ "$RESULTADO" = "10" ]
	then
	dpkg-reconfigure xserver-xorg
	fi

	if [ $RESULTADO = "0" ] 
	then
	# NOTE: podemos dejarlo establecido para cuando reinicie
	# pero no podemos usar este método acá, debemos comunicarnos
	# con opciones-inicio.sh para que sepa que queremos configurar
	# el video, y lance el script y luego reinicie X
	# Para esto creamos un flag
	cat /dev/null > /tmp/configure-video
	# luego dejamos esto para el próximo reinicio
	rm /usr/sbin/mkxf86config
	ln -s /bin/xorgmusix.sh /usr/sbin/mkxf86config
	#xorgmusix.sh # esto se ejecuta desde opciones-inicio.sh
	AUTODETECT="yes"
	AUTODETECTM="Musix's new method"
	opciones-inicio.sh &
	sudo killall kdm
	sudo killall Xorg
	sudo killall X
	fi


	if [ $RESULTADO = "1" ] 
	then		
	rm /usr/sbin/mkxf86config
	ln -s /usr/sbin/mkxf86config-musix /usr/sbin/mkxf86config
	mkxf86config
	AUTODETECT="yes"
	AUTODETECTM="musix"
	fi
	
	# no necesita función
	if [ $RESULTADO = "2" ] 
	then		
	rm /usr/sbin/mkxf86config
	ln -s /usr/sbin/mkxf86config-gentoo /usr/sbin/mkxf86config
	mkxf86config
	AUTODETECT="yes"
	AUTODETECTM="gentoo"
	fi

	if [ $RESULTADO = "3" ] 
	then		
	# this is a link, so we just remove it
	rm /usr/sbin/mkxf86config
	AUTODETECT="no"
	AUTODETECTM="-"
	
	
	fi

	if [ $RESULTADO = "4" ] 
	then
	# FIXME: esto es muy brutal!		
	#sudo killall kdm
	sudo killall Xorg && kdm
	sudo killall X && kdm
	#sudo killall XFree86
	#sudo killall Xorg
	#sleep 3s
	#kdm
	#startx 
	#sleep 5s
	
	kdm
	
	
	fi

	# Listando ritmos
	if [ $RESULTADO = "5" ] 
	then		
	cp /etc/X11/xorg.conf.bak $XCONFIG
	
	
	fi

	# Abrimos el midi con $SEQ
	if [ $RESULTADO = "6" ] 
	then		
	echo "elinks /usr/doc/musix/index.html &"
	elinks /usr/doc/musix/index.html
	
	
	fi

	if [ $RESULTADO = "7" ] 
	then
	echo "Editando"
	nano $XCONFIG
		
	
	fi


	if [ $RESULTADO = "8" ] 
	then
	# TODO: check if it's allready into 800x600
	sed s/\"1024x768\"\ \"800x600\"\ \"640x480\"/\"800x600\"\ \"640x480\"/g $XCONFIG > /tmp/temp
	cp /tmp/temp $XCONFIG
	fi

	if [ $RESULTADO = "9" ] 
	then
	# TODO: check if it's allready into 1024x768
	sed s/\"800x600\"\ \"640x480\"/\"1024x768\"\ \"800x600\"\ \"640x480\"/g $XCONFIG > /tmp/temp
	cp /tmp/temp $XCONFIG
	fi

	#if [ $RESULTADO = 10 ] 
	#then
	#kwrite /boot/grub/menu.lst
	#
	#fi

	#if [ $RESULTADO = 10 ] 
	#then
	#krandrtray &
	#
	#exit
	#fi

done

}

# Definición de una función:
funcion-video(){

echo "debug!2"

EXIT="no"
while [ $EXIT="no" ]
do

# lo configuramos para salir por default...
rm -f /tmp/salida
RESULTADO=11
#kdialog --menu "
#Autodetection: $AUTODETECT
#Method: $AUTODETECTM
#
#X server config options /// Opciones para el servidor X
#Elige una opción /// Choose an option
#
#" "0: Enable autodetection method 0: Musix's new method" "1: Enable autodetection method #1: Musix knoppix's method" "2: Enable autodetection method 2: Gentoo live-cd's method" "3: Disable video autodetection / Desabilitar autodetección de video" "4: Restart X to test your changes / Reiniciar X para probar los cambios" "5: Restore X config / Restaurar configuración de X" "6: Help docs / Ayuda" "7: /etc/X11/xorg.conf manual edit" "8: Force X resolution to 800x600" "9: Set X resolution to 1024x768" "10: krandrtray" "11: Exit" > /tmp/salida


kdialog --radiolist "
Autodetection: $AUTODETECT
Method: $AUTODETECTM

X server config options /// Opciones para el servidor X
Elige una opción /// Choose an option
----------------------------------------------------------------------------------------------------
" "0" "0: Enable autodetection method 0: Musix's new method" "1" "1" "1: Enable autodetection method 1: Musix knoppix's method" "2" "2" "2: Enable autodetection method 2: Gentoo live-cd's method" "3" "3" "3: Disable video autodetection / Desabilitar autodetección de video" "4" "4" "4: Restart X to test your changes / Reiniciar X para probar los cambios" "5" "5" "5: Restore X config / Restaurar configuración de X" "6" "6" "6: Help docs / Ayuda" "7" "7" "7: /etc/X11/xorg.conf manual edit" "8" "8" "8: Force X resolution to 800x600" "9" "9" "9: Set X resolution to 1024x768" "10" "10" "10: krandrtray" "11" "11" "11: Exit" "11: Exit" "11" > /tmp/salida



RESULTADO=`cat /tmp/salida | cut -f1 -d":"`
#export RESULTADO=$?
echo Su elección fue $RESULTADO

# cerramos la definición de la función funcion-video

# sale si no existe la variable!
[ -z $RESULTADO ] && exit 

	if [ $RESULTADO = "0" ] 
	then
	# NOTE: podemos dejarlo establecido para cuando reinicie
	# pero no podemos usar este método acá, debemos comunicarnos
	# con opciones-inicio.sh para que sepa que queremos configurar
	# el video, y lance el script y luego reinicie X
	# Para esto creamos un flag
	cat /dev/null > /tmp/configure-video
	# luego dejamos esto para el próximo reinicio
	rm /usr/sbin/mkxf86config
	ln -s /bin/xorgmusix.sh /usr/sbin/mkxf86config
	#xorgmusix.sh # esto se ejecuta desde opciones-inicio.sh
	AUTODETECT="yes"
	AUTODETECTM="Musix's new method"
	opciones-inicio.sh &
	sudo killall kdm
	sudo killall Xorg && opciones-inicio.sh
	sudo killall X && opciones-inicio.sh
	fi

	if [ $RESULTADO = "11" ] 
	then
	echo "Saliendo..."
	exit 0
	fi

	if [ $RESULTADO = "1" ] 
	then		
	rm /usr/sbin/mkxf86config
	ln -s /usr/sbin/mkxf86config-musix /usr/sbin/mkxf86config
	mkxf86config
	AUTODETECT="yes"
	AUTODETECTM="musix knoppix"
	
	fi
	
	# no necesita función
	if [ $RESULTADO = "2" ] 
	then		
	rm /usr/sbin/mkxf86config
	ln -s /usr/sbin/mkxf86config-gentoo /usr/sbin/mkxf86config
	mkxf86config
	AUTODETECT="yes"
	AUTODETECTM="gentoo"
	
	fi

	if [ $RESULTADO = "3" ] 
	then		
	# this is a link, so we just remove it
	rm /usr/sbin/mkxf86config
	AUTODETECT="no"
	AUTODETECTM="-"
	
	fi

	if [ $RESULTADO = "4" ] 
	then
	# FIXME: esto es muy brutal!		
	#sudo killall kdm
	sudo killall Xorg && kdm
	sudo killall X && kdm
	#sudo killall XFree86
	#sudo killall Xorg
	#sleep 3s
	#kdm
	#startx 
	#sleep 5s
	# TODO: ver cómo recargar el programa automáticamente
	#
	exit
	fi

	# Listando ritmos
	if [ $RESULTADO = "5" ] 
	then		
	cp /etc/X11/xorg.conf.bak $XCONFIG
	
	fi

	# Abrimos el midi con $SEQ
	if [ $RESULTADO = "6" ] 
	then		
	$BROWSER $MANUALINDEX &
	
	fi

	if [ $RESULTADO = "7" ] 
	then
	echo "Editando"
	$TEXTED $XCONFIG
	
	fi


	if [ $RESULTADO = "8" ] 
	then
	# TODO: check if it's allready into 800x600
	sed s/\"1024x768\"\ \"800x600\"\ \"640x480\"/\"800x600\"\ \"640x480\"/g $XCONFIG > /tmp/temp
	cp /tmp/temp $XCONFIG
	
	fi

	if [ $RESULTADO = "9" ] 
	then
	# TODO: check if it's allready into 1024x768
	sed s/\"800x600\"\ \"640x480\"/\"1024x768\"\ \"800x600\"\ \"640x480\"/g $XCONFIG > /tmp/temp
	cp /tmp/temp $XCONFIG
	
	fi

	#if [ $RESULTADO = 10 ] 
	#then
	#kwrite /boot/grub/menu.lst
	#
	#fi

	if [ $RESULTADO = "10" ] 
	then
	krandrtray &
	
	fi
# desabilitar autodetección
# restaurar config
#krandrtray

done

}


probar_X && x=1

if [ "$x" != "1" ]; then
	echo "No estamos en X"
	configconsola
	opciones-inicio.sh
	exit
else
	echo "Estamos en X"
	funcion-video
	exit
fi


killall2 mkxf86config
killall2 videoconfig

exit
