#!/bin/bash

# failsafe
#set -e

#
# usage
#
function usage()
{
    ADDUSER_PATH="$SBOX_PATH/sbin/sbox_adduser"
    cat <<EOF

Usage: $MYNAME
       $MYNAME -|-s
       $MYNAME <OPTIONS> <COMMAND> [<ARGS>]

Options:
       -d <DIR> change cwd to DIR before running command
       -e <MY_ENV> use MY_ENV as BASH_ENV. (see man bash)
       -p print commands as they are executed
       -k keep current environment

Starts a Scratchbox session.  If no arguments are given, an interactive login
shell is launched.  If a dash or '-s' is specified, the stdin is executed as
a shell script.  Otherwise the arguments are executed by the shell.  If the
'-d' option is specified, the current directory will be changed first.

You need to have a Scratchbox user account in order to log in.  It can be
created by root using $ADDUSER_PATH.

EOF
    exit 1
}

#
# print welcome message
#
function print_welcome()
{
    echo
    echo "Welcome to Scratchbox, the cross-compilation toolkit!"
    echo
    echo "Use 'sb-menu' to change your compilation target."
    echo "See /scratchbox/doc/ for documentation."
    echo
}

#
# exit point in case of error
#
function exit_error()
{
    echo -e "ERROR: "$@
    exit 1
}

#
# do some basic checks to see if environment is ok
#
function sanity_check()
{
    if [ `id -u` = 0 ] ; then
	exit_error "Not allowed to run this as root!"
    fi
    if [ ! -d $SANDBOX ]; then
	exit_error "You don't have a Scratchbox user account!"
    fi
    if [ ! -d $SANDBOX/scratchbox/tools/bin ] || [ ! -c $SANDBOX/dev/null ]; then
	exit_error "Scratchbox is not properly set up!"
    fi
}

#
# sudo mode initialization routines
#
function sudo_mode()
{
    SUDO=sudo
    CHROOT_CMD="$SBOX_PATH/sbin/chroot-sudo-uid"

    if [ ! -f $CHROOT_SUDO ]; then
        exit_error "ERROR: $CHROOT_SUDO is missing!"
    fi

    # register arm binaries (only for sudomode)
    $SUDO $SBOX_PATH/sbin/register_misc_runner

    # do mount --bind:ing (only for sudomode)
    mkdir -p $SANDBOX/proc $SANDBOX/tmp $SANDBOX/scratchbox $SANDBOX/dev

    if ! mount | grep -q " on $SANDBOX/proc" ; then
	$SUDO mount --bind /proc $SANDBOX/proc
    fi
    if ! mount | grep -q " on $SANDBOX/tmp" ; then
	$SUDO mount --bind /tmp $SANDBOX/tmp
    fi
    if ! mount | grep -q " on $SANDBOX/scratchbox" ; then
	$SUDO mount --bind $SBOX_PATH $SANDBOX/scratchbox
    fi
    if [ -d /scratchbox_local/dev ]; then
	if ! mount | grep -q " on $SANDBOX/dev" ; then
	    $SUDO mount --bind /scratchbox_local/dev $SANDBOX/dev
	fi
    fi
    if ! mount | grep -q " on $SANDBOX/dev/pts" ; then
	$SUDO mount -t devpts none $SANDBOX/dev/pts
    fi

    CHROOT_CMD="$SUDO $CHROOT_SUDO"
}

#
# normal mode initialization
#
function normal_mode()
{
    CHROOT_CMD="$SBOX_PATH/sbin/chroot-uid"
    if [ ! -f "$CHROOT_CMD" ]; then
	exit_error "'$CHROOT_CMD' is missing."
    fi
    if [ ! -u "$CHROOT_CMD" ]; then
	exit_error "'$CHROOT_CMD' is not suid ROOT."
    fi
    if [ ! -x "$CHROOT_CMD" ]; then
	exit_error "You don't have permission to run '$CHROOT_CMD'.\nMaybe you have not logged out and in again after being added to sbox group."
    fi
}

#
# Create some stuff for user if running first time
#
function initialize_sbox()
{
    # Create stuff for user
    if [ ! -L $SANDBOX/home/$USER/.terminfo ]; then
	ln -s /scratchbox/etc/terminfo $SANDBOX/home/$USER/.terminfo
    fi
    create_target
}

#
# run sb-menu for user
#
create_target()
{
    if [ ! -L "$SANDBOX/targets/links/scratchbox.config" ] ; then
	echo
	echo "You dont have active target in scratchbox chroot.";
	echo "Please create one by running \"sb-menu\" before continuing";
	echo
    fi
}



#
# set up scratchbox specific environment variables
#
function sboxify_environment()
{
    export _SBOX_USER_GROUPNAME=`groups | cut -d' ' -f1`

    export _SBOX_DIR=$SBOX_PATH

    export PATH=/scratchbox/tools/bin:/scratchbox/compilers/bin:/bin:/usr/bin

    export SBOX_REDIRECT_FROM_DIRS=/bin:/usr/bin
    export SBOX_REDIRECT_TO_DIRS=/scratchbox/tools/bin

    export SBOX_PRELOAD=/scratchbox/tools/lib/libsb.so.0
    if [ $MYENV ] ; then
	    export BASH_ENV=$MYENV
	    SBENV="$SBENV"' BASH_ENV="$BASH_ENV"'
    fi
    export HOME=/home/$USER

    SBENV="$SBENV"' _SBOX_USER_GROUPNAME="$_SBOX_USER_GROUPNAME" _SBOX_DIR="$SBOX_PATH" PATH="$PATH" SBOX_REDIRECT_FROM_DIRS="$SBOX_REDIRECT_FROM_DIRS"'
    SBENV="$SBENV"' SBOX_REDIRECT_TO_DIRS="$SBOX_REDIRECT_TO_DIRS" SBOX_PRELOAD="$SBOX_PRELOAD" HOME="$HOME"'
    SBENV="$SBENV"' USER="$USER" TERM="$TERM" LOGNAME="$LOGNAME"'
}


#
# resolve where scratchbox is installed
#
function resolve_sbox_path()
{
    if ! which dirname > /dev/null 2>&1 ; then
	exit_error "'dirname' command is needed to run this script"
    fi
    if ! which readlink > /dev/null 2>&1 ; then
	exit_error "'readlink' command is needed to run this script"
    fi
    SBOX_PATH=`dirname $(readlink -f "$0")`
    SANDBOX="$SBOX_PATH/users/$USER"
}

#
# run scratchbox command
#
function run_sbox_command()
{
    if $STDIN ; then
	if $ECHO ; then
	    echo $RUN -s
	fi
	$RUN -s
	RETURN=$?
    else
	if $ECHO ; then
	    echo $RUN /scratchbox/tools/bin/exec.sh "$INITIAL_DIR" "$@"
	fi
	$RUN /scratchbox/tools/bin/exec.sh "$INITIAL_DIR" "$@"
	RETURN=$?
    fi
}

#
# run interactive shell
#
function run_sbox_shell()
{
    print_welcome
    export _SBOX_RESTART_FILE=/tmp/scratchbox-restart.$USER
    SBENV="$SBENV"' _SBOX_RESTART_FILE="$_SBOX_RESTART_FILE"'
    $RUN
    while [ -f $_SBOX_RESTART_FILE ]; do
	reset
	rm $_SBOX_RESTART_FILE
	echo "Shell restarting..."
	$RUN
    done
}

#
# clean up
# unmount sbox directories if there is no more active sessions left
#
function cleanup()
{
	PYTHON="$CHROOT_CMD $SANDBOX /scratchbox/tools/bin/python"
    if [ "`$PYTHON /scratchbox/tools/bin/sb-conf ls -S|wc -l`" = 1 ]; then
	 $PYTHON /scratchbox/tools/bin/sbrsh-conf umount >/dev/null
    fi
}

#
# ready, set, GO!
#
MYNAME=${0/*\//}
INITIAL_DIR="/home/$USER"
MYENV=""
STDIN=false
ECHO=false
KEEPENV=false

resolve_sbox_path

. $SBOX_PATH/sbin/compatibility.sh

# use scratchbox's python
PYTHON="$SBOX_PATH/host_shared/lib/ld.so --library-path $SBOX_PATH/host_shared/lib $SBOX_PATH/tools/bin/python"

#
# parse arguments
#
while getopts d:e:pksh inst
do
  case $inst in
	(d) INITIAL_DIR="$OPTARG" ;;
	(e) MYENV="$OPTARG" ;;
	(p) ECHO=true ;;
	(s) STDIN=true ;;
	(k) KEEPENV=true ;;
	(*) usage ;;
  esac
done
shift $(($OPTIND - 1))
if [ "$1" = "-" ] ; then
    STDIN=true
fi


sanity_check
if [ -f $SBOX_PATH/.sudo_mode ]; then
    sudo_mode
else
    normal_mode
fi
sboxify_environment
if $KEEPENV; then
  RUN="$CHROOT_CMD $SANDBOX /scratchbox/tools/bin/bash -l"
else
  RUN="eval eval $CHROOT_CMD $SANDBOX /scratchbox/tools/bin/env - \$SBENV /scratchbox/tools/bin/bash -l"
fi
initialize_sbox

trap true HUP

if [ $# -gt 0 -o "$STDIN" = true ] ; then
    run_sbox_command "$@"
else
    run_sbox_shell
fi

cleanup

trap true TERM

if [ $RETURN ] ; then
    exit $RETURN
fi

# kill the script process group (everything run from this script)
kill -- -$$
