#!/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.
#-----------------------------------------------------------------------------

#  postflight.sh
#  Lili
#
#  Copyright (c) 2012 LogMeIn. All rights reserved.
#
#  Runs as root

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

BUNDLEPATH=$2
ROOTPATH=$3
FILELIST=$4     # The format of the file containing file metadata is: path:owner:group:permissions

function getVersion()
{
    if [ ! -r "$1" ]; then
        return 1;
    fi

    local FOUND=0
    local line
    while read line || [[ -n "${line}" ]]; do
        local L=${line#<*>}
        L=${L%<*}
        if [ $FOUND -eq 0 ]; then
    	    if [ "$L" == "CFBundleVersion" ]; then
                FOUND=1
            fi
        else
            echo $L
            return 0
        fi
    done <"$1"
    return 2
}

function Run()
{
    # try to remove already existing LogMeInRemoteUser (and fail silently)
    dscl . -delete /users/LogMeInRemoteUser >/dev/null 2>&1

    # Check if new license requested, therefore we have a new config.xml
    if [ -f /tmp/temporary.com.logmein.newconfig.xml ] ; then
        echo "replacing config.xml"  
        cp -f "/Library/Application Support/LogMeIn/config.xml" "/Library/Application Support/LogMeIn/config.xml.bak" 2>/dev/null || true 
        cp -f /tmp/temporary.com.logmein.newconfig.xml "/Library/Application Support/LogMeIn/config.xml"  2>&1
        rm -f /tmp/temporary.com.logmein.newconfig.xml
    else
        echo "replacing config.xml was not needed"
    fi

    # check on which OS version we run
    V=$(sw_vers -productVersion | awk -F. '{print $2}')

    # remove update folder
    echo "Removing update folder"
    rm -rf "/Library/Application Support/LogMeIn/update"

    # create symlinks for printer
    echo "Creating symlinks for the printer driver"
    rm -rf /usr/libexec/cups/backend/LogMeInBackend                                                                                                                                  
    rm -rf /usr/libexec/cups/filter/LogMeInFilter                                                                                                                                    
    rm -rf /usr/libexec/cups/filter/commandtoLogMeIn                                                                                                                                 
                                                                                                                                                                                     
    ln -sf /Library/Printers/LogMeIn/LogMeInPrinter.bundle/Contents/MacOS/commandtoLogMeIn /usr/libexec/cups/filter                                                                  
    ln -sf /Library/Printers/LogMeIn/LogMeInPrinter.bundle/Contents/MacOS/LogMeInFilter /usr/libexec/cups/filter                                                                     
    mkdir -p /usr/libexec/cups/backend                                                                                                                                               
    ln -sf /Library/Printers/LogMeIn/LogMeInPrinter.bundle/Contents/MacOS/LogMeInBackend /usr/libexec/cups/backend                                                                   

    # check if we're under Lion
    if [ $V -eq 7 ]; then
        # We need this workaround now on lion because of pre-login agents could hang at leaving login screen bug in OSX - LMIMAC-1483
        defaults write "/Library/LaunchAgents/com.logmein.logmeinguiagentatlogin.plist" EnableTransactions -bool TRUE
        defaults write "/Library/LaunchAgents/com.logmein.logmeinguiagentatlogin.plist" ExitTimeOut -int 10
        defaults write "/Library/LaunchAgents/com.logmein.logmeinguiagent.plist" EnableTransactions -bool TRUE
        defaults write "/Library/LaunchAgents/com.logmein.logmeinguiagent.plist" ExitTimeOut -int 10
        chmod 644 "/Library/LaunchAgents/com.logmein.logmeinguiagentatlogin.plist"
        chmod 644 "/Library/LaunchAgents/com.logmein.logmeinguiagent.plist"
    fi

    # Replace the sound driver
    cp -Rf "/Library/Application Support/LogMeIn/drivers/LogMeInSoundDriver.kext" /System/Library/Extensions
    # Let the host load the driver on demand
    #kextload -v /System/Library/Extensions/LogMeInSoundDriver.kext

    # Hide Ignition beacuse of Continuum, host will reenable if needed
    chflags hidden "/Applications/LogMeInIgnition.app"

    #
    # Do not do this! Leave root_updates in place to let them be used for further update cycles without downloading again!
    #
    #if [ -d "/Library/Application Support/LogMeIn/root_updates" ] ; then
    #  echo "Remove the root_updates folder" 
    #  rm -rf "/Library/Application Support/LogMeIn/root_updates"
    #fi

    # start the plugin installer if present and  not yet installed or older than we have in host installer
    INSTALLER_PATH=$(find "${BUNDLEPATH}/Contents/Resources/" -name "LogMeIn Plugin Installer*.app")
    if [ -d "$INSTALLER_PATH" ]; then
        PLUGIN_VERSION=`getVersion "$INSTALLER_PATH/Contents/Info.plist"`
        INSTALLED_PLUGIN_VERSION=`getVersion "/Library/Internet Plug-Ins/LogMeInSafari32.plugin/Contents/Info.plist"`
        echo "Plugin version:           $PLUGIN_VERSION"
        echo "Installed plugin version: $INSTALLED_PLUGIN_VERSION"
        PLUGIN_BUILD=${PLUGIN_VERSION##*.}
        INSTALLED_PLUGIN_BUILD=${INSTALLED_PLUGIN_VERSION##*.}

        if [ 0${PLUGIN_BUILD} -gt 0${INSTALLED_PLUGIN_BUILD} ]; then
            echo "Installing plugin"
            "$INSTALLER_PATH/Contents/MacOS/Lili" --silent
        fi
    else
        echo "No plugin installer found, skipping."
    fi

    # Make sure at this point no other still stopping service process remained,
    # that instance might broadcasts stop messages during shutdown that could stop
    # the new instance that will start right now from postcheck.sh
    # Because of 10.10 launchd/launchctl changes take care of other possibly still running agents too, kill them all also

    # Try the normal way first, now we have the latest logmeinserverctl installed
    "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" stop
    sleep 2
    "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" disable

    echo "Killing LogMeIn processes if any is still alive"
    killall -KILL LogMeIn
    # Yes these are keepalive agents, but at least this way will be surely restarted
    killall -KILL LMIGUIAgent
    killall -KILL LogMeInGUI
    sleep 2

    rm -Rf   /tmp/LogMeIn
    rm -Rf   "/Library/Application Support/LogMeIn/run"
    mkdir -p "/Library/Application Support/LogMeIn/run/Guards"
}


if [ "x$FILELIST" == "x" ]; then echo "postflight: missing input filename"; exit 1; fi
if [ "x$ROOTPATH" == "x" ]; then echo "postflight: missing root path"; exit 1; fi

echo "postflight: started with file(s) $FILELIST on 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 "postflight: 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
