#!/bin/sh
#
# Tazx - Ncurses X configuration for SliTaz GNU/Linux using Dialog boxes.
# This tinyutil is part of slitaz-tools. Tazx can configure Xorg with 
# several Window Managers. The GTK interface to configure X is in tazbox.
#
# (c) 2011-2014 SliTaz GNU/Linux - GNU GPL v3.
# Authors: Christophe Lincoln <pankso@slitaz.org>
#          Pascal Bellard <pascal.bellard@slitaz.org>
#

# 20140317: most xsession, xinitrc are obsolete, provided system files
# are in /etc/skel and WM config files should no longer be copied by
# tazx to user home. If some configs are needed by WMs they should
# be set by a /usr/bin/wmname-session script I guess. - Pankso

. /lib/libtaz.sh
. /etc/slitaz/slitaz.conf
. /etc/slitaz/applications.conf

installed="$PKGS_DB/installed"

export TEXTDOMAIN='slitaz-tools' #i18n
: ${DIALOG=dialog}

# Default value.
WM=${WINDOW_MANAGER}

# Default user for config files in Live mode, id is 1000 since it is
# created by /etc/init.d/bootopts.sh.
USER=$(cat /etc/passwd | grep 1000 | cut -d ":" -f 1)

#
# Functions
#

# Save chunk of xorg.conf into specified file
save_chunk() {
	sed -e '/Section "'${1#*-}'"/,/EndSection/!d' \
		-e "s/EndSection/EndSection\n/" $xorg_template > \
		$xorg_config/$1.conf
}

# Populate xorg.conf.d.
xorg_conf_d() {
	# Define the xorg.conf.d (can be /etc/X11/xorg.conf.d or /usr/share/X11/xorg.conf.d)
	xorg_config=/etc/X11/xorg.conf.d

	# Define the xorg.conf.new place.
	xorg_template=/root/xorg.conf.new

	# Obtain a default configuration file from Xorg.
	Xorg -configure :2

	# Backup existing config.
	tar -cf $xorg_config/../Previous_xorg.conf.d.tar $xorg_config/ &> /dev/null 

	# Put the different sections in separate files in the config directory.
	save_chunk 10-ServerLayout
	sed -i '/Core/d' $xorg_config/10-ServerLayout.conf
	save_chunk 20-Files
	save_chunk 30-Module
	save_chunk 50-Monitor
	save_chunk 60-Device
	save_chunk 70-Screen

	# Remove the template.
	rm $xorg_template

	# Configure the keyboard with the right keymap.
	keymap=$(cat /etc/keymap.conf)
	keyboard_config=$xorg_config/40-Keyboard.conf
	variant=""
	# this XkbOption moved from 40-evdev.conf (xorg-xf86-input-evdev)
	options="terminate:ctrl_alt_bksp"
	case $keymap in
		fr_CH-latin1)
			# Swiss FrenCH
			layout="ch"; variant="fr" ;;
		uk)
			# English UK
			layout="gb" ;;
		ru)
			# Russian
			layout="us,ru"
			options="grp:ctrl_shift_toggle, grp_led:scroll, $options" ;;
		ua)
			# Ukrainian
			layout="us,ua,ru"
			options="grp:ctrl_shift_toggle, $options" ;;
		slovene)
			# Slovenian
			layout="si"; options="grp:alt_shift_toggle, $options" ;;
		us-acentos)
			layout="us"; variant="intl" ;;
		*)
			# Use clean /etc/keymap.conf value.
			keymap=${keymap%-latin1}
			keymap=${keymap%-lat2}
			keymap=${keymap%-lat6}
			layout=${keymap%-abnt2}
	esac

	cat > $keyboard_config << EOC
Section "InputClass"
	Identifier "Keyboard Defaults"
	MatchIsKeyboard "yes"
	Option "XkbLayout" "$layout"
	Option "XkbVariant" "$variant"
	Option "XkbOptions" "$options"
EndSection
EOC
	[ x$variant == x ] && sed -i '/XkbVariant/d' $keyboard_config

	# Create a xorg.conf if needed.
	if [ ! -f /etc/X11/xorg.conf ]; then
	cat > /etc/X11/xorg.conf << EOT
# You can put here your own Xorg configurations. This config file is read
# before all files in /etc/X11/xorg.conf.d and will NOT be erased by any
# updates.
EOT
	fi
}

# Install xorg server.
install_xorg() {
	[ -f "/var/lib/tazpkg/packages.list" ] || tazpkg recharge
	exec 3>&1
	value=$($DIALOG \
		--clear --colors \
		--title " $(_n 'Install Xorg') " \
		--menu "$(_n 'Tazx helps you to select your X driver.')" 16 70 8 \
	$(fgrep xorg-xf86-video /var/lib/tazpkg/packages.list | cut -d- -f4 | \
		while read x; do echo $x; _ 'driver'; done) \
	"quit" "$(_n 'Quit')" \
	2>&1 1>&3)
	retval=$?
	exec 3>&-

	# Continue or exit.
	case $retval in
		0) continue ;;
		1|255) exit 0 ;;
	esac

	# Set selected value.
	case $value in
		quit) exit 0 ;;
		*)
			[ -d "$installed/xorg-server" ] || tazpkg -gi xorg-server
			[ -d "$installed/xorg-xf86-video-$value" ] || \
				tazpkg -gi xorg-xf86-video-$value
			xorg_conf_d ;;
	esac
}

# Screen configuration dialog. TODO: menus items to enable/disable X on boot
# and sed /etc/rcS.conf to remove slim from RUN_DAEMONS.
config_dialog() {
	exec 3>&1
	value=$($DIALOG \
		--clear --colors \
		--title "{ $(_n 'SliTaz Xorg config') }" \
		--menu "" 16 72 10 \
	"xorg"        "$(_n 'Install or reconfigure Xorg')" \
	"xorg-light"  "$(_n 'Install Xorg server (light version)')" \
	"quit"        "$(_n 'Quit Tazx utility')" \
	2>&1 1>&3)
	retval=$?
	exec 3>&-

	# Continue or exit.
	case $retval in
		0) continue ;;
		1|255) exit 0 ;;
	esac

	# Set selected value.
	case "$value" in
		xorg) 
			install_xorg ;;
		xorg-light)
			[ -d "$installed/xorg-server-light" ] || \
				tazpkg -gi xorg-server-light
			[ -d "$installed/xorg-xf86-video-fbdev" ] || \
				tazpkg -gi xorg-xf86-video-fbdev
			xorg_conf_d ;;
		*)
			exit 0 ;;
	esac
}

# ~/.xinitrc for X login from a DM.
creat_xinitrc() {
	apps_conf=/etc/slitaz/applications.conf
	user_conf="$HOME/.config/slitaz/applications.conf"
	xinitrc="$HOME/.xinitrc"
	if [ ! -f "$user_conf" ]; then
		mkdir -p $(dirname $user_conf); cp ${apps_conf} ${user_conf}
	fi
	if [ ! -f "$xinitrc" ]; then
		cp /etc/skel/.xinitrc ${xinitrc}
	fi

	# Make .xinitrc and config for /etc/skel so new added user will get
	# a working X session.
	if test $(id -u) = 0; then
		user_conf="/etc/skel/.config/slitaz/applications.conf"
		mkdir -p $(dirname $user_conf); cp -f ${apps_conf} ${user_conf}
	fi

	# In Live mode default user needs a xinitrc, since tazx is executed
	# only by root.
	user_conf="/home/$USER/.config/slitaz/applications.conf"
	xinitrc="/home/$USER/.xinitrc"
	if [ ! -f "$user_conf" ]; then
		mkdir -p $(dirname $user_conf); cp ${apps_conf} ${user_conf}
		chown -R $USER.users $(dirname $user_conf)
	fi
	if [ ! -f "$xinitrc" ]; then
		cp -f /etc/skel/.xinitrc ${xinitrc}
		chown $USER.users ${xinitrc}
	fi
}

# Create ~/.xsession to keep the configuration selected (used
# only by startx, Slim login manager uses .xinitrc).
creat_xsession() {
	local xsession=$HOME/.xsession
	[ -f "$xsession" ] && cp -f ${xsession} ${xsession}.bak
	cat > ${xsession} << EOT
# ~/.xsession: Start X session manually on your system with: startx
#
Xorg &
#xterm &
exec $WM
EOT
	chmod 700 ${xsession}
}

# Commands

case "$1" in
	install-xorg)
		check_root
		install_xorg
		creat_xinitrc
		creat_xsession ;;
	
	config-xorg)
		check_root
		creat_xinitrc
		creat_xsession
		xorg_conf_d
		# Handle live option: screen=
		if grep -qs screen= /proc/cmdline ; then
			MODE="$(sed 's/.*screen=\([0-9]*x[0-9]*\).*/\1/' < /proc/cmdline)"
			sed -i "s/.*EndSubSection.*/\\t\\tModes\\t\"$MODE\"\\n&/" \
				/etc/X11/xorg.conf.d/70-Screen.conf
		fi ;;
	
	*help) 
		echo "Usage: $(basename $0) [install-xorg|config-xorg|]" ;;
	
	*)
		# User can get a new .xinitrc with tazx from cmdline.
		[ $(id -u) == 0 ] && config_dialog
		creat_xinitrc
		creat_xsession ;;
esac

exit 0
