#!/bin/bash
##
## Copyright (C) Centeris Corporation 2004-2007
## Copyright (C) Likewise Software 2007.  
## All rights reserved.
## 
## 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 3 of the License, 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
## along with this program.  If not, see <http:##www.gnu.org/licenses/>.
##


export CENTERIS_SCRIPT_WRAPPER=domainjoin-gui
PREFIX=/opt/likewise-open
ASSEMBLY=$PREFIX/bin/DomainJoin.exe
ID_PROG=id
MONO_HOME=/usr
LIB_DIR=$PREFIX/lib

function invoke_mono
{
    if [ -n "${MONO_OVERRIDE}" ]; then
	echo "Using mono out of alternate location \[${MONO_OVERRIDE}\]"
	MONO_HOME=${MONO_OVERRIDE}
    fi

    if [ -d ${LIB_DIR} ]; then
        export LD_LIBRARY_PATH=${LIB_DIR}:${LD_LIBRARY_PATH}
    fi

    if [ -d ${MONO_HOME} ]; then
        MONO=${MONO_HOME}/bin/mono
        export LD_LIBRARY_PATH=${MONO_HOME}/lib:${LD_LIBRARY_PATH}
        export MONO_PATH=${MONO_HOME}/lib/mono/2.0
        if [ -d ${MONO_HOME}/etc/fonts ]; then
            export FONTCONFIG_PATH=${MONO_HOME}/etc/fonts:${FONTCONFIG_PATH}
        fi
    else
        MONO=`type -p mono`
        if [ -z "${MONO}"]; then
            echo "Mono was not found on this system."
            exit 1
        fi
    fi

    assembly="$1"
    shift

    # For nicer GUI look-and-feel
    export MONO_THEME=nice

    if [ "$1" = "--mono-version" ]; then
        shift
        MONO_VERSION=`${MONO} --version 2>/dev/null | head -1 | perl -p -e '$_ =~ s/^.*version +([0-9.-]+).*/$1/'`
        echo "Using mono version ${MONO_VERSION} at ${MONO}"
    fi
    umask 022
    ${MONO} "${assembly}" "$@"
    exit $?
}

if [ "`echo $CENTERIS_SCRIPT_WRAPPER | grep 'gui$'`" = "$CENTERIS_SCRIPT_WRAPPER" -a -z "$DISPLAY" ]; then
    echo "This application must be run from a graphical display."
    echo "For a command-line version, try `echo $CENTERIS_SCRIPT_WRAPPER | sed 's/gui$/cli/'`."
    exit 1
fi

invoke_mono "${ASSEMBLY}" "$@"
