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

#  preflight.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

function Run()
{
    echo "Killing Toolkit process"
    killall -TERM Toolkit
    sleep 2
    killall -KILL Toolkit

    echo "Killing Ignition process"
    killall -TERM LogMeInIgnition
    killall -TERM "LogMeIn Ignition"
    sleep 2
    killall -KILL LogMeInIgnition
    killall -KILL "LogMeIn Ignition"

    echo "Stopping running daemons and agents..."
    # Try the bruteforce first
    launchctl stop /Library/LaunchDaemons/com.logmein.logmeinserver.plist
    launchctl unload -w /Library/LaunchDaemons/com.logmein.logmeinserver.plist
    launchctl unload -w /Library/LaunchDaemons/com.logmein.logmeinblanker.plist
    launchctl unload -w /Library/LaunchDaemons/com.logmein.raupdate.plist
    launchctl unload -w /Library/LaunchAgents/com.logmein.LMILaunchAgentFixer.plist
    launchctl unload -w -S Aqua /Library/LaunchAgents/com.logmein.logmeingui.plist
    launchctl unload -w -S Aqua /Library/LaunchAgents/com.logmein.logmeinguiagent.plist
    launchctl unload -w -S LoginWindow /Library/LaunchAgents/com.logmein.logmeinguiagentatlogin.plist
    # Try the normal way just to be sure
    if [ -f "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" ]; then
        "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" stop
        sleep 2
        "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" disable
        sleep 2
    fi
	#Try to stop legacy logmeinserver
    if [ -f "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Resources/logmeinserverctl" ]; then
        "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Resources/logmeinserverctl" stop
        sleep 2
        "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Resources/logmeinserverctl" disable
        sleep 2
    fi

    echo "Removing obsolote files, dirs..."

    # remove garbage from root:
    if [ -f /config.xml ] && [ -n "`grep '<key name="/" tstamp=' /config.xml`" ] ; then
      rm /config.xml
    fi
    if [ -f /config.bak.xml ] && [ -n "`grep '<key name="/" tstamp=' /config.bak.xml`" ] ; then
      rm /config.bak.xml
    fi
    if [ -f /server.pem ] ; then
      rm /server.pem
    fi
    if [ -f /CA.pem ] ; then
      rm /CA.pem
    fi

    # remove obsolete receipts
    rm -rf "/Library/Receipts/LogMeIn Server Installer.pkg" 

    # remove obsolete files/version
    rm -rf "/etc/pam.d/logmein"
    rm -rf "/Library/StartupItems/LogMeInGui.bundle/"

    # LMIMAC-1540 - The RemoteSoundDriver is renamed to LogMeInSoundDriver, so the old named have to remove
    # Now we only have a unibin sound driver named LogMeInSoundDriver.kext
    if [ -d "/System/Library/Extensions/RemoteSoundDriver32.kext" ] ; then
        echo "Unload and remove RemoteSoundDriver32"
        kextunload "/System/Library/Extensions/RemoteSoundDriver32.kext"
        kextunload "/System/Library/Extensions/RemoteSoundDriver32.kext"
        rm -rf "/System/Library/Extensions/RemoteSoundDriver32.kext"
    fi
    if [ -d "/System/Library/Extensions/RemoteSoundDriver64.kext" ] ; then
        echo "Unload and remove RemoteSoundDriver64"
        kextunload "/System/Library/Extensions/RemoteSoundDriver64.kext"
        kextunload "/System/Library/Extensions/RemoteSoundDriver64.kext"
        rm -rf "/System/Library/Extensions/RemoteSoundDriver64.kext"
    fi
    if [ -d "/System/Library/Extensions/LogMeInSoundDriver32.kext" ] ; then
        echo "Unload and remove LogMeInSoundDriver32"
        kextunload "/System/Library/Extensions/LogMeInSoundDriver32.kext"
        kextunload "/System/Library/Extensions/LogMeInSoundDriver32.kext"
        rm -rf "/System/Library/Extensions/LogMeInSoundDriver32.kext"
    fi
    if [ -d "/System/Library/Extensions/LogMeInSoundDriver64.kext" ] ; then
        echo "Unload and remove LogMeInSoundDriver64"
        kextunload "/System/Library/Extensions/LogMeInSoundDriver64.kext"
        kextunload "/System/Library/Extensions/LogMeInSoundDriver64.kext"
        rm -rf "/System/Library/Extensions/LogMeInSoundDriver64.kext"
    fi
    if [ -d "/System/Library/Extensions/LogMeInSoundDriver.kext" ] ; then
        echo "Unload LogMeInSoundDriver64"
        kextunload "/System/Library/Extensions/LogMeInSoundDriver.kext"
        kextunload "/System/Library/Extensions/LogMeInSoundDriver.kext"
        # we will refresh this in postupdate so can be removed too
        rm -fR "/System/Library/Extensions/LogMeInSoundDriver.kext"
    fi

    # LMIMAC-1522 - Remove the LogMeIn folder from the Application folder, no longer used. - 2011.10.17.
    # but replace the LogMeInPluginUninstaller.app if any
    if [ -e "/Applications/LogMeIn/LogMeInPluginUninstaller.app" ]; then
        echo "Moving LogMeInPluginUninstaller.app into the support directory"
        if [ -d "/Library/Application Support/LogMeIn Plugin" ] ; then
            echo "Moving LogMeInPluginUninstaller.app into the support directory"
        else
            echo "Moving LogMeInPluginUninstaller.app into the new support directory"
            mkdir "/Library/Application Support/LogMeIn Plugin"
        fi
        mv -f /Applications/LogMeIn/LogMeInPluginUninstaller.app "/Library/Application Support/LogMeIn Plugin"
    fi 
    if [ -d "/Applications/LogMeIn" ] ; then
        echo "Removing old /Application/LogMeIn directory"
        rm -rf "/Applications/LogMeIn"
    fi

    local LMI_SUPPORT_DIR="/Library/Application Support/LogMeIn"
    local CONFIG_XML="$LMI_SUPPORT_DIR/config.xml"
    local BACKUP_DIR="/tmp/backup_of_LogMeIn_config/"

    rm -rf "${BACKUP_DIR}"
    # Backup config.xml and *.pem files because of the cleanup below
    if [ -d "$LMI_SUPPORT_DIR" ]; then
        mkdir -p "${BACKUP_DIR}"
        echo "Backing up $CONFIG_XML"
        mv -f "$CONFIG_XML" "$BACKUP_DIR" || echo "Unable to back up $CONFIG_XML"
        echo "Backing up certs"
        mv -f "$LMI_SUPPORT_DIR/"*.pem "$BACKUP_DIR" || echo "Unable to back up certs"
    fi

    local OLD_LOG_DIR="$LMI_SUPPORT_DIR/log"
    local NEW_LOG_DIR="/Library/Logs/LogMeIn"
    local BACKUP_LOG_DIR="/tmp/backup_of_LogMeIn_log"

    rm -rf "${BACKUP_LOG_DIR}"
    # Backup log files because of the cleanup below
    echo "Backing up logs ($OLD_LOG_DIR and/or $NEW_LOG_DIR)"
    mkdir -p "${BACKUP_LOG_DIR}"
    mv -f "${NEW_LOG_DIR}/"* "${BACKUP_LOG_DIR}" # Some older versions already have logs here and may have links here too
    mv -f "${OLD_LOG_DIR}/"* "${BACKUP_LOG_DIR}"

    # cleanup everything, new installer will always add all the neccessary files from now
    echo "Removing /Applications/LogMeIn Ignition.app/ directory"
    rm -rf "/Applications/LogMeIn Ignition.app"
    rm -rf "/Applications/LogMeInIgnition.app"

    echo "Removing /Library/LaunchAgents/com.logmein.*"
    rm -f  "/Library/LaunchAgents/com.logmein.LMILaunchAgentFixer.plist"
    rm -f  "/Library/LaunchAgents/com.logmein.logmeingui.plist"
    rm -f  "/Library/LaunchAgents/com.logmein.logmeinguiagent.plist"
    rm -f  "/Library/LaunchAgents/com.logmein.logmeinguiagentatlogin.plist"

    echo "Removing /Library/LaunchDaemons/com.logmein.*"
    rm -f  "/Library/LaunchDaemons/com.logmein.logmeinserver.plist"
    rm -f  "/Library/LaunchDaemons/com.logmein.logmeinblanker.plist"
    rm -f  "/Library/LaunchDaemons/com.logmein.raupdate.plist"

    # remove LMI components from launchdb
    if [ -f "/Library/Application Support/LogMeIn/cleanlaunchdb.sh" ] ; then
        source "/Library/Application Support/LogMeIn/cleanlaunchdb.sh" #2>&1 | tee -a "${LOGFILE}"
    fi

    # this is to be sure blanker is disabled in launch db and plist too
    "/Library/Application Support/LogMeIn/bin/LogMeIn.app/Contents/Helpers/logmeinserverctl" stop blanking

    # remove our authorization db entry, to be sure an entry format change would have no affect on the auth process
    security authorizationdb remove com.logmein.logmein.login

    echo "Removing /Applications/Toolkit.app/ directory"
    rm -rf "/Applications/Toolkit.app"

    echo "Removing /Library/Printers/LogMeIn/ directory"
    rm -rf "/Library/Printers/LogMeIn"

    # Do this as a final step!
    echo "Removing $LMI_SUPPORT_DIR directory"
    rm -rf "$LMI_SUPPORT_DIR"
    rm -rf "$NEW_LOG_DIR"

    # Cleanup finished start to restore backup of important files
    mkdir -p "$LMI_SUPPORT_DIR"
    mkdir -p "$NEW_LOG_DIR"

    # Restore log files if any because of the cleanup above
    if [ -d "${BACKUP_LOG_DIR}" ]; then
        echo "Restoring ${NEW_LOG_DIR}"
        mv -f "${BACKUP_LOG_DIR}/"* "$NEW_LOG_DIR" || echo "Unable to restore $NEW_LOG_DIR"
        rm -rf "${BACKUP_LOG_DIR}"
    fi

    # Let everyone write and add new log files
    chmod +a "staff allow add_file" "${NEW_LOG_DIR}"
    echo "" >> "${NEW_LOG_DIR}/LogMeIn.log"
    chmod 666 "${NEW_LOG_DIR}/LogMeIn.log"
    ln -s "$NEW_LOG_DIR" "$OLD_LOG_DIR"

    # Restore config.xml and *.pem files if any because of the cleanup above
    if [ -d "$BACKUP_DIR" ]; then
        echo "Restoring $CONFIG_XML and server certificates"
        mv -f "$BACKUP_DIR"* "$LMI_SUPPORT_DIR" || echo "Unable to restore $CONFIG_XML and/or server certificates"
        chmod 600 "$LMI_SUPPORT_DIR"/*.pem
        rm -rf "${BACKUP_DIR}"
    fi

    # remove temp garbages
    rm -rf "/var/tmp/"com.logmein.*
    rm -rf "/tmp/"com.logmein.*
    rm -rf "/tmp/"LMIPS*.sock
    rm -rf "/tmp/"LogMeIn*
    rm -rf "/tmp/"lmiprinter.sock
    rm -rf "/tmp/LogMeIn/"*
    rm -rf "/tmp/"temporary.com.logmein.*
}

echo "preflight: 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 "preflight: 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

