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

# Do not use yet, $USER can be unset during runtime
#set -u             # Treat unset variables as an error when performing parameter expansion.

#set -e             # Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-zero status.
shopt -s extdebug   # If set, behavior intended for use by debuggers is enabled
#shopt -s extglob   # If set, the extended pattern matching features of Pathname Expansion are enabled.
#-----------------------------------------------------------------------------

LAUNCH_DB="/private/var/db/launchd.db"
LMI_IDS=(
"com.logmein.logmeinblanker" \
"com.logmein.logmeinblankeratlogin" \
"com.logmein.logmeingui" \
"com.logmein.logmeinguiagent" \
"com.logmein.logmeinguiagentatlogin" \
"com.logmein.LMILaunchAgentFixer" \
"com.logmein.logmeinserver" \
"com.logmein.raupdate" \
)
LIST_ONLY=0
# check on which OS version we run
OSVERSION=$(sw_vers -productVersion | awk -F. '{print $2}')

function get_owner()
{
    local OWNER=

    if [ -f "$1" ]; then
        OWNER=$(ls -Al "$1" | awk '{ print $3; }')
    else
        local DIR=$(echo "$1" | awk -F \/ '{ print $NF; }')
        OWNER=$(ls -Al "$1/.." | awk 'BEGIN { pattern="'${DIR}'"; } { if ($9 == pattern) print $3; }')
    fi
    echo $OWNER
}

echo "cleanlaunchdb.sh started (with param num: $#, param(s): $*)"
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)"
echo

if [ $# -ge 1 ]; then
    if [ $# -eq 1 ] && [ "${1}" == "--listonly" ]; then      # TODO: Remove fix position dependency
        LIST_ONLY=1
        shift 1
    else
        echo -e "\nUnknown parameter(s), num=$# : $*"
        echo -e "\nUsage: $0 [--listonly]"
        exit 1
    fi
fi

if [ $LIST_ONLY == 0 ]; then
    echo "Cleaning up launch DB..."
else
    echo "Listing launch DB..."

fi

for FILE in $(find "$LAUNCH_DB" -name overrides.plist -type f -depth 2); do
    if [ -f "$FILE" ] && [ -s "$FILE" ]; then
        DIR=$(dirname "$FILE")
        PLIST_FILE="$FILE"
        echo "Handling launch db: $DIR"

        if [ $OSVERSION -lt 7 ]; then   # on Leopard or earlier defaults need the plist file without extension
            BASE_NAME=$(basename "${FILE}" .plist)
            PLIST_FILE="${DIR}/${BASE_NAME}"
        fi

        for ID in "${LMI_IDS[@]}"; do
            HAS_ID=$(defaults read "$PLIST_FILE" $ID 2>&1 | grep -i "$ID) does not exist")
            #echo "HAS ID $ID = $HAS_ID"

            if [ $LIST_ONLY == 0 ] && [ "$HAS_ID" == "" ]; then
                echo "Removing $ID"
                defaults delete "$PLIST_FILE" $ID
            fi
        done
        DIROWNER=$(get_owner "$DIR")
        FILEOWNER=$(get_owner "$FILE")
        if [ "$DIROWNER" != "$FILEOWNER" ]; then
            echo -e "Owner of $FILE should be $DIROWNER"
            echo -e "Owner of $FILE is $FILEOWNER"
            echo -e "Setting owner to $DIROWNER:wheel of $FILE"
            chown $DIROWNER:wheel "$FILE"
            FILEOWNER=$(get_owner "$FILE")
            echo -e "Owner of $FILE is $FILEOWNER"
        fi
        echo -e "Resulting DB content:"
        defaults read "$PLIST_FILE" | grep -i logmein -A 2
        echo -e "Finished $FILE\n\n"
    fi
done

