#!/bin/sh 

# input from user
command=$1
user=$2
installdir="$3"
datadir="$4"
force=$5

PATH=/usr/bin:${PATH}
export PATH

MyOS=`uname`
if [ "$MyOS" = "SunOS" ]; then
    id=/usr/xpg4/bin/id
elif [ "$MyOS" = "HP-UX" ]; then
    id=/usr/bin/id
elif [ "$MyOS" = "AIX" ]; then
    id=/bin/id
else
    id=id
fi

umask 0077
/bin/chmod 755 "$datadir" > /dev/null 2>&1
# run registry and rpcss in different directories so we get to keep core files
# if they're dumped.
/bin/mkdir -p "${datadir}/rpcss_run"  > /dev/null 2>&1
/bin/mkdir -p "${datadir}/registry_run"  > /dev/null 2>&1

MWHOME="$installdir/mw"
export MWHOME
HOME="$datadir"
export HOME


MWREG_BACKUP_DIR="$HOME/registry_backup"
export MWREG_BACKUP_DIR

. "$MWHOME/setmwruntime"

# always use the installation registry file
MWREGISTRY="${datadir}/.mw/hklm_${MWCONFIG_NAME}.bin"
export MWREGISTRY

PATH="${HOME}:${PATH}"
export PATH

. /etc/mainwin.conf

if [ ${MWRPC_ENDPOINT:-"not_set"} = "not_set" ]; then
 MWRPC_ENDPOINT=$CORE_RPC_ENDPOINT
 export MWRPC_ENDPOINT
fi

curuser=`$id -u -n`
if [ "${curuser:-}" != "${user:-}" ] ; then
    uid=`$id -u ${user:-}`
    exec_as_user $uid noenv $0 $command $user "$installdir" "$datadir"
    if [ $? -ne 0 ]; then 
        # Start of core services failed, probably due to permissions to su to user ${user:-}
        exit 1
    fi
# The work was done by the exec_as_user instance, no need to continue.
# The reason we don't just exec it is that we want to control the exit status.
    exit 0
fi

exec "${MWHOME}/bin/tools/core_services.common" $command "$datadir" $force
