#!/bin/sh
#
# Copyright (c) 2002 by James A. McQuillan (McQuillan Systems, LLC)
#
# This software is licensed under the Gnu General Public License version 2,
# the full text of which can be found in the COPYING file.
#

# Deprecated: /usr/lib/ltsp/screen.d is for compatibility reasons, will be removed one day
SCRIPT_DIRS="/etc/ltsp/screen.d /usr/share/ltsp/screen.d /usr/lib/ltsp/screen.d"

# Load LTSP configuration
if [ "True" != "$LTSP_CONFIG" ]; then
    . /usr/share/ltsp/ltsp_config
fi

# Figure out SCREEN_NUM
if [ -n "$1" ]; then
    SCREEN_NUM="$1"
    TTY_NUM=${SCREEN_NUM#0}
    TTY=/dev/tty$TTY_NUM
    exec <$TTY >$TTY 2>&1           # redirect stdin/out/err to our tty
else
    # If screen_session is called from inittab/upstart, already with a
    # controlling terminal, then just figure out what screen number we are.
    TTY=`tty`
    case $TTY in
        /dev/tty?) SCREEN_NUM="0${TTY##/dev/tty}" ;;
        /dev/tty??) SCREEN_NUM="${TTY##/dev/tty}" ;;
    esac
fi

export SCREEN_NUM
eval SCREEN_CMD=\$\{SCREEN_$SCREEN_NUM\}

SCREEN_SCRIPT=`echo $SCREEN_CMD | cut -f1 -d" "`
SCREEN_ARGS=`echo $SCREEN_CMD | cut -f2- -d" " -s`

if [ "${SCREEN_NUM}" = "01" ]; then
    logger -t LTSP "Screen scripts should not be run on SCREEN_01"
    echo "SCREEN_01 Contains a screen script ${SCREEN_SCRIPT} ${SCREEN_ARGS} Please change to another screen"
    exit 1
fi

for SCRIPT_DIR in ${SCRIPT_DIRS}; do
    if [ -x ${SCRIPT_DIR}/${SCREEN_SCRIPT} ]; then
        if [ "${SCRIPT_DIR}" = "/usr/lib/ltsp/screen.d" ]; then
            echo "Warning: /usr/lib/ltsp/screen.d is deprecated and will be removed in the future."
            echo "         ${SCREEN_SCRIPT} requires updating to use /usr/share/ltsp."
        fi
        exec ${SCRIPT_DIR}/${SCREEN_SCRIPT} ${SCREEN_ARGS}
    fi
done

logger -t LTSP "Screen:${TTY} - SCREEN_SCRIPT: ${SCREEN_SCRIPT} not found!"
echo "Screen:${TTY} - SCREEN_SCRIPT: ${SCREEN_SCRIPT} not found!"
