#!/bin/bash

function removePathIfExists {
    local description=$1
    local path=$2
    local user=$3
    local skipCheck=$4

    if test -z "${skipCheck}"; then
        /bin/echo "Checking ${description} path ${path}"
        echo /usr/bin/sudo -u "${user}" -- /bin/bash -c "test -e \"${path}\" 2>/dev/null"
        /usr/bin/sudo -u "${user}" -- /bin/bash -c "test -e \"${path}\" 2>/dev/null"
    fi

    if test $? -eq 0 -o -n "${skipCheck}"; then
        /bin/echo "Removing ${description}"
        /bin/echo -n [3m
        /usr/bin/sudo -u "${user}" -- /bin/rm -rvf "${path}"
        /bin/echo -n [0m
    else
        /bin/echo Nothing found
    fi
}

function removeJobIfExists {
    local description=$1
    local plist=$2
    if test -f "${plist}"; then
        /bin/echo "Unloading $description"
        /usr/bin/sudo /bin/launchctl unload "${plist}"
        /bin/echo "Deleting $description job definition"
        /bin/echo -n  [3m
        /usr/bin/sudo rm -vf "${plist}"
        /bin/echo -n  [0m
    fi
}

function processUser {
    local user=$1

    home=$(/usr/bin/dscl localonly -read "/Local/Default/Users/${user}" NFSHomeDirectory \
            | /usr/bin/sed 's/^NFSHomeDirectory: //')
    /bin/echo "[1mProcessing user ${user}[0m"

    removePathIfExists "HTTP Storage" "${home}/Library/HTTPStorages/com.soma-zone.BackupLoupe" "${user}"
    removePathIfExists "WebKit Storage" "${home}/Library/WebKit/com.soma-zone.BackupLoupe" "${user}"
    removePathIfExists "application support folder" "${home}/Library/Application Support/BackupLoupe" "${user}"
    removePathIfExists "saved application state" "${home}/Library/Saved Application State/com.soma-zone.BackupLoupe.savedState" "${user}"
    sudo -u "${user}" -- /usr/bin/find "${home}/Library/Application Support/CrashReporter" -name 'BackupLoupe_*' -delete
    sudo -u "${user}" -- /usr/bin/find "${home}/Library/Application Support/CrashReporter" -name 'com.soma-zone.BackupLoupe_*' -delete

    if (( remove_monitor == 1 )); then
        removeJobIfExists "local monitor", "${home}/Library/LaunchAgents/com.soma-zone.BackupLoupe.Monitor.plist"
    fi

    if (( remove_prefs == 1 )); then
        /usr/bin/sudo -u "${user}" -- /bin/rm -vf "${home}/Library/Preferences/com.soma-zone.BackupLoupe.Scanner.plist"
    fi

    /usr/bin/sudo -u "${user}" -- /usr/bin/defaults read com.soma-zone.BackupLoupe >/dev/null 2>/dev/null
    if test $? -eq 0; then
        /bin/echo "Found BackupLoupe preferences for user ${user}"

        if (( remove_caches == 1 )); then
            localCaches=$(/usr/bin/sudo -- /usr/libexec/PlistBuddy -c 'Print cachePath' "${home}/Library/Preferences/com.soma-zone.BackupLoupe.plist" 2>/dev/null)
            if test -n "${localCaches}"; then
                localCaches=$(/bin/echo "${localCaches}" | sed "s|^~|${home}|")
                removePathIfExists "custom local cache" "${localCaches}" "${user}"
            fi
        fi

        if (( remove_prefs == 1 )); then
            /bin/echo Deleting BackupLoupe preferences
            /usr/bin/sudo -u "${user}" -- /usr/bin/defaults delete com.soma-zone.BackupLoupe
            /bin/echo -n  [3m
            /usr/bin/sudo -u "${user}" -- /bin/rm -v "${home}/Library/Preferences/com.soma-zone.BackupLoupe.plist"
            /bin/echo -n  [0m
        fi
    fi
    if (( remove_caches == 1 )); then
        localCaches="${home}/Library/Caches/com.soma-zone.BackupLoupe"
        removePathIfExists "old default local cache" "${localCaches}" "${user}"
        localCaches="${home}/Library/BackupLoupe"
        removePathIfExists "new default local cache" "${localCaches}" "${user}"
    fi

    if (( remove_logs == 1 )); then
        localLogs="${home}/Library/Logs/BackupLoupe"
        removePathIfExists "local logs" "${localLogs}" "${user}"
    fi
}

function usage {
    echo "$0 --all [--keep-prefs] [--keep-group] [--keep-logs] [--keep-caches] [--keep-monitor] [--keep-helper] [--keep-app]"
    echo "$0 [--remove-prefs] [--remove-group] [--remove-logs] [--remove-caches] [--remove-monitor] [--remove-helper] [--remove-app]"
}

function init {
    if (( $# == 0 )); then
        remove_prefs=1
        remove_logs=1
        remove_group=1
        remove_caches=1
        remove_monitor=1
        remove_helper=1
        remove_app=1
        /bin/echo -n "This script will remove every trace of BackupLoupe from your system. Do you want to continue? (yes/NO): "
        read -r reply
        if test "${reply}" != "yes"; then
            echo Script aborted.
            exit 0
        fi
    else
        remove_prefs=0
        remove_logs=0
        remove_group=0
        remove_caches=0
        remove_monitor=0
        remove_helper=0
        remove_app=0
    fi
    for arg in "$@"; do
        if test "$arg" == "--all"; then
            remove_prefs=1
            remove_group=1
            remove_logs=1
            remove_caches=1
            remove_monitor=1
            remove_app=1
            remove_helper=1
        elif test "$arg" == "--keep-prefs"; then
            remove_prefs=0
        elif test "$arg" == "--keep-logs"; then
            remove_logs=0
        elif test "$arg" == "--keep-group"; then
            remove_group=0
        elif test "$arg" == "--keep-caches"; then
            remove_caches=0
        elif test "$arg" == "--keep-monitor"; then
            remove_monitor=0
        elif test "$arg" == "--keep-helper"; then
            remove_helper=0
        elif test "$arg" == "--keep-app"; then
            remove_app=0

        elif test "$arg" == "--remove-prefs"; then
            remove_prefs=1
        elif test "$arg" == "--remove-logs"; then
            remove_logs=1
        elif test "$arg" == "--remove-group"; then
            remove_group=1
        elif test "$arg" == "--remove-caches"; then
            remove_caches=1
        elif test "$arg" == "--remove-monitor"; then
            remove_monitor=1
        elif test "$arg" == "--remove-helper"; then
            remove_helper=1
        elif test "$arg" == "--remove-app"; then
            remove_app=1
        elif test "$arg" == "--help" -o "$arg" == "-h"; then
            usage
            exit 0
        elif test "${arg:0:1}" == "-"; then
            echo "Unknown option: $arg"
            usage
            exit 1
        else
            echo "Invalid argument: $arg"
            usage
            exit 1
        fi
    done
}

init "$@"

sudo true
if test $? -ne 0; then
        echo "Aborting…"
        exit 1
fi

/usr/bin/dscl localonly -list /Local/Default/Users \
        | grep -v -e '^_' -e '^Guest$' -e '^daemon$' -e '^root$' -e '^nobody$' \
        | while read -r user; do
    processUser "${user}"
done

/bin/echo [1mProcessing global files[0m
globalPrefs=/Library/Preferences/com.soma-zone.BackupLoupe.plist
if test -f "${globalPrefs}"; then
    if (( remove_caches == 1 )); then
        globalCaches=$(/usr/libexec/PlistBuddy -c 'Print cachePath' "${globalPrefs}" 2>/dev/null)
        if test -n "${globalCaches}"; then
            removePathIfExists "custom global cache" "${globalCaches}" "root"
        fi
    fi
    if (( remove_prefs == 1 )); then
        removePathIfExists "global monitor configuration" "${globalPrefs}" "root" "skipCheck"
    fi
fi

if (( remove_caches == 1 )); then
    globalCaches=/Library/Caches/com.soma-zone.BackupLoupe
    removePathIfExists "old default global cache" "${globalCaches}" "root"
    globalCaches=/Library/BackupLoupe
    removePathIfExists "new default global cache" "${globalCaches}" "root"
fi

if (( remove_monitor == 1 )); then
    removeJobIfExists "global monitor" "/Library/LaunchDaemons/com.soma-zone.BackupLoupe.Monitor.plist"
fi
if (( remove_helper == 1 )); then
    removeJobIfExists "helper tool" "/Library/LaunchDaemons/com.soma-zone.BackupLoupe.Helper.plist"
    removePathIfExists "helper tool" "/Library/PrivilegedHelperTools/com.soma-zone.BackupLoupe.Helper" "root"
fi

if (( remove_group == 1 )); then
    /bin/echo Checking for group com.soma-zone.BackupLoupe
    /usr/sbin/dseditgroup -o read com.soma-zone.BackupLoupe >/dev/null 2>&1
    if test $? -eq 0; then
        /bin/echo Deleting group
        /usr/bin/sudo /usr/sbin/dseditgroup -o delete com.soma-zone.BackupLoupe >/dev/null 2>/tmp/uninstall-backuploupe.err
        if test $? -ne 0; then
            /bin/echo Failed to delete group:
            /bin/cat /tmp/uninstall-backuploupe.err
        fi
    else
        /bin/echo No such group
    fi
fi

if (( remove_logs == 1 )); then
    globalLogs="/Library/Logs/BackupLoupe"
    removePathIfExists "global logs" "${globalLogs}" "root"
fi

if (( remove_app == 1 )); then
    /bin/echo Looking for BackupLoupe application bundles
    IFS=$'\n'; for app in $(/usr/bin/mdfind "kMDItemCFBundleIdentifier == 'com.soma-zone.BackupLoupe'"); do
        version=$(/usr/libexec/PlistBuddy -c 'Print CFBundleShortVersionString' "${app}/Contents/Info.plist")
        /bin/echo -n "Found ${app} (${version}); Do you want to delete it? (yes/NO): "
        read -r reply
        if test "${reply}" == "yes"; then
            /bin/echo "[3m${app}[0m"
            /usr/bin/sudo rm -rf "${app}"
        else
            /bin/echo Skipped
        fi
    done
fi

/bin/echo Uninstall completed.
