#!/bin/sh

export PATH=/usr/bin:/bin:/usr/sbin:/sbin

# relaunch MSC.app if it was running before we upgraded it
MSC_APP="/Applications/Managed Software Center.app"

if [ "$3" == "/" ]; then
    if [ -e /tmp/com.googlecode.munki.relaunch_msc_app ] ; then
        FRONTMOST=$(cat /tmp/com.googlecode.munki.relaunch_msc_app)
        rm /tmp/com.googlecode.munki.relaunch_msc_app
        if [ "$FRONTMOST" == "frontmost" ] ; then
            OPENCMD="open -a"
        else
            OPENCMD="open -g -a"
        fi
        CONSOLEUSER=$(who | grep console | cut -d" " -f1)
        if [ "$CONSOLEUSER" == "" ] ; then
            exit 0
        fi
        CONSOLE_UID=$(id -u "$CONSOLEUSER")
        os_build_version=$(sw_vers -buildVersion | cut -b 1-2)
        for pid_uid in $(ps -axo pid,uid,args | grep -i "[l]oginwindow.app" | awk '{print $1 "," $2}'); do
            pid=$(echo $pid_uid | cut -d, -f1)
            uid=$(echo $pid_uid | cut -d, -f2)
            if [ "$uid" == "$CONSOLE_UID" ] ; then
                if [[ $os_build_version -lt 14 ]] ; then
                    launchctl bsexec "$pid" chroot -u "$uid" / $OPENCMD "$MSC_APP"
                    exit 0
                else
                    launchctl asuser "$uid" $OPENCMD "$MSC_APP"
                    exit 0
                fi
            fi
        done
    fi
fi
