#!/bin/bash -p
#
#   If  the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied,
#   no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS variable, if it appears in the environment,
#   is ignored, and the effective user id is set to the real user id.
#   If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset.
#-----------------------------------------------------------------------------

#  postcheck.sh
#  Lili
#
#  Copyright (c) 2012 LogMeIn. All rights reserved.
#
#  Runs as the current user

LOGFILE=$1
exec 2>&1 # >>$LOGFILE   We do not need this anymore, script runners capture script outputs

BUNDLEPATH=$2
ROOTPATH=$3

function Run()
{
    V=$(sw_vers -productVersion | awk -F. '{print $2}')

    if [ $V -lt 10 ]; then  # prior to Yosemite launchctl could not start the agents in the correct user session, so trying to correct that bug
        echo "Starting the daemon and all agents"
        
        # load and start the server service (only to let agents run in good context even if started elevated)
        "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Resources/logmeinserverctl" start serveronly

        sleep 2 # wait for server to start

        local SESSION_TYPE="-S Aqua"
        
        # start the gui as the current interactive user. it will be started by logmeinserverctl later, but
        # would not allow interactive authorization.
        echo "launchctl load -w $SESSION_TYPE /Library/LaunchAgents/com.logmein.logmeingui.plist"
        launchctl load -w $SESSION_TYPE /Library/LaunchAgents/com.logmein.logmeingui.plist
        echo "launchctl load -w $SESSION_TYPE /Library/LaunchAgents/com.logmein.logmeinguiagent.plist"
        launchctl load -w $SESSION_TYPE /Library/LaunchAgents/com.logmein.logmeinguiagent.plist

        # load guiagent at loginscreen (the remaining one)
    fi
    "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" start
}

echo "postcheck: started with path $ROOTPATH and bundlepath $BUNDLEPATH"
echo "current uid=${UID}, gid=$( id | awk -F= '/gid=/ { print $3 }' | awk -F\(  '{ print $1 }' ), euid=${EUID}, egig=$(id -g), user=${USER}"
echo "id=$(id)"

Run 

echo -n "postcheck: finished"

# return 0 in case of success
# return 253 in case of success but signal user logoff required to finalize install
# return 254 in case of success but signal OS restart required to finalize install
# return 255 or a negative value in case of errors

exit 0
