#!/bin/sh
# $Id$
#
# fbset:	Sets up fbcon video modes.
#
#
# chkconfig:	2345 69 31
# description:	fbset is a utility with which fbcons video modes can be read \
#		and changed
#
# config:	/etc/sysconfig/fbset

# Get service config
if [ -f /etc/sysconfig/fbset ]; then
	. /etc/sysconfig/fbset
fi

if [ -z "${FBMODULE}" ]; then
   	case "$1" in
	start|stop|restart|force-reload)
		exit 0
		;;
	esac
fi

# Source function library
. /etc/rc.d/init.d/functions

# Setting default depth
if [ -n "${DEPTH}" ]; then
	DEPTH_options="-depth ${DEPTH}"
fi

if [ -z "${FBDEV_NUM}" ]; then
	FBDEV_NUM=0
fi

start() {
	# Check if service is already running?
	if [ ! -f /var/lock/subsys/fbset ]; then

		# Check if we have framebuffer in kernel.
		local load_fbmodule=1
		if [ -f /proc/fb ]; then
			# /proc files show as files with size=0, this is a workaround.
			grep -q '.' /proc/fb && load_fbmodule=0
		fi

		if [ "$load_fbmodule" = "1" ]; then
			modprobe $FBMODULE
		fi

		if [ -n "${FBMODE_default}" ]; then
			show "Setting default video mode"
			busy

			local cons tty devpath
			# check if devfs
			if [ -d /dev/vc ]; then
				if [ -z "$FBTERMINALS" ]; then
					FBTERMINALS=$(ls /dev/vc/)
				fi
				FBDEV=/dev/fb/$FBDEV_NUM
				devpath=/dev/vc/
			else
				if [ -z "$FBTERMINALS" -a -d /dev/.udev ]; then
					FBTERMINALS=$(ls /dev/vcsa* | awk '{print substr($0, length("/dev/vcsa") + 1)}')
				fi
				if [ -z "$FBTERMINALS" -a -d /sys/class/vc ]; then
					FBTERMINALS=$(ls -d /sys/class/vc/vcsa* | awk '{print substr($0, length("/sys/class/vc/vcsa") + 1)}')
				fi
				if [ -z "$FBTERMINALS" ]; then
					FBTERMINALS=$(awk -F: '/^[0-9]*:/{print $1}' /etc/inittab)
				fi
				FBDEV=/dev/fb$FBDEV_NUM
				devpath=/dev/tty
			fi

			# save old tty number
			tty=$(/usr/bin/tty)
			tty=${tty#$devpath}

			for cons in $FBTERMINALS; do
				/usr/bin/con2fb $FBDEV $cons
				/usr/bin/switchto $cons
				/usr/bin/fbset -fb \
				  $FBDEV $DEPTH_options $FBMODE_default \
				  0<>/dev/tty$cons >&0 2>&0
			done
			[ $tty = "/dev/console" ] && tty=1
			/usr/bin/switchto $tty
			ok
		fi
		touch /var/lock/subsys/fbset
	else
		msg_already_running fbset
	fi
}

stop() {
	if [ -f /var/lock/subsys/fbset ]; then
		rm -f /var/lock/subsys/fbset
	else
		msg_not_running fbset
	fi
}

# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  status)
	# Check if we have framebuffer in kernel.
	if [ -f /proc/fb ] && grep -q . /proc/fb; then
	   	nls "Frame buffer present."
		exit 0
	fi

	nls "Frame buffer not present."
	exit 3
	;;
  restart|force-reload)
	stop
	start
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status}"
	exit 3
esac

exit 0
