# common code to ltsp x screen scripts

# Copyright (c) 2002 by James A. McQuillan (McQuillan Systems, LLC)
# Copyright (c) 2008 by Warren Togami      (Red Hat, Inc.)
# Copyright (c) 2008 by Vagrant Cascadian
#
# This software is licensed under the GNU General Public License version 2,
# the full text of which can be found in the COPYING file.

# Copyright 2005, Canonical Ltd.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License with your
# Debian GNU system, in /usr/share/common-licenses/GPL.  If not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

#
# Load ltsp config defaults
#

. /usr/share/ltsp/ltsp-common-functions
if ! boolean_is_true "$LTSP_CONFIG" ; then
    . /usr/share/ltsp/ltsp_config
fi

#
# Compute tty and display
#

TTY=$(tty)
TTY=${TTY#/dev/tty}
DISP=":$TTY"

error_delay() {
    echo -n -e "\n\rERROR: $1"
    read CMD
}

#
# limit ram percentage.  By default, behaviour is 90%.
# Use this to stop firefox crashing sites with pathalogically large images,
# etc.
#

XMem=$(($(MemInfo MemFree)+$(MemInfo Cached)))
[ -n "$X_RAMPERC" ] && XMem=$(($XMem * $X_RAMPERC)) || XMem=$((($XMem + $(MemInfo SwapFree)) * ${X_VRAMPERC:-90}))
XMem=$(($XMem / 100))
ulimit -v $XMem
echo "=== X server limited to $XMem kB ${X_VRAMPERC:+Virtual }RAM ==="
unset XMem


### configuration file handling

X_CONF="${X_CONF:-/var/run/ltsp-xorg.conf}"

if [ -f "$X_CONF" ]; then
    X_ARGS="$X_ARGS -config $X_CONF"
else
    echo
    echo "Error! - ${X_CONF} - File not found!"
    echo
fi

### color depth

X_ARGS="$X_ARGS${X_COLOR_DEPTH:+ -depth $X_COLOR_DEPTH}"

### default fonts

X_ARGS="$X_ARGS${X_FONTS:+ -fp $X_FONTS}"

# XFS handling
# implemented as a function so it could be called on sucessive tries

get_xfs_settings() {
    # set default font path
    # use XFS_SERVER if defined, otherwise
    # attempt to use servers passed on commandline

    local port SRV
    if boolean_is_true "$USE_XFS" ; then
	for SRV in ${XFS_SERVER:-$@}; do
	    port="${SRV#*:}"
	    [ "$SRV" = "$port" ] && port="7100"
	    X_ARGS="$X_ARGS -fp tcp/${SRV%:*}:$port"
	done
    fi
}
