#!/bin/sh

#  UninstallPrivilegedHelper.sh
#  BackupLoupe
#
#  Created by Robby Pählig on 28.12.2018.
#  

echo $(basename $0) started at $(date)
echo $0 $@

identifier=$1
if [[ -z "${identifier}" ]]; then
	echo Usage: $(basename $0) IDENTIFIER TMPFILE
	exit 1
fi

tmpfile=$2
if [[ -z "${tmpfile}" ]]; then
	echo Usage: $(basename $0) IDENTIFIER TMPFILE
	exit 2
fi

if [[ ! -d "${tmpfile}" ]]; then
    echo File $tmpfile does not exist
	echo Usage: $(basename $0) IDENTIFIER TMPFILE
	exit 3
fi

plistPath="/Library/LaunchDaemons/${identifier}.plist"
privilegedHelperPath="/Library/PrivilegedHelperTools/${identifier}"

echo $(basename $0) started at $(date)
echo Script was started w/ uid $(id -u) and real uid $(id -ur): $0 $@

if [[ -f "$plistPath" ]]; then
	launchctl list ${identifier} > /dev/null
	if [[ $? -eq 0 ]]; then
		echo Unloading job.
		launchctl unload "${plistPath}"
    else
		echo Job is currently not loaded
	fi

	echo Removing job property list
	rm "${plistPath}"
else
	echo Job ${plistPath} not installed
fi

if [[ -f "${privilegedHelperPath}" ]]; then
	echo Removing privileged helper tool
	rm -f "${privilegedHelperPath}"
else
	echo Privileged helper tool not installed
fi

echo Removing lock file ${tmpfile}…
rmdir "${tmpfile}"
