#!/bin/bash

PARTIAL=false
NUKE_CUSTOMIZATIONS=true

while getopts uc opt
do
    case "$opt" in
	u) PARTIAL=true
            ;;
	c) NUKE_CUSTOMIZATIONS=false
	    ;;
	\?) echo "Usage: $0"
            exit 1
            ;;
    esac
done

MAGIC=/var/db/.com.f-secure.fsmac.uninstall
LOG="/Library/Logs/F-Secure Mac Protection uninstall.log"
MSGLOG="/Library/Logs/F-Secure Mac Protection uninstall messages.log"
PKGUTIL=/usr/sbin/pkgutil
NOUNINSTALL="/usr/local/f-secure/fsmac/sysconfig/.no_uninstall"

echo > "$MSGLOG"
date "+%Y-%m-%d %T: Uninstall script starting (upgrade=${PARTIAL}): $0 $*" >> "$LOG"
fsav --version >> "$LOG" 2>&1
syslog -s -l Critical "Uninstall script starting (upgrade=${PARTIAL}): $0 $*"

exec 1>>"$LOG"
exec 2>>"$LOG"

uname -a

set -x

if [ -f $NOUNINSTALL -a $PARTIAL == false ] ; then
    {
	echo
	echo "Uninstallation disallowed"
    echo
    } >> "$MSGLOG"
    syslog -s -l Critical "Uninstallation disallowed"
    exit 1
fi

if [ -r "`dirname $0`/safer_remove_dir" ] ; then
    . "`dirname $0`/safer_remove_dir"
elif [ -r /usr/local/f-secure/bin/safer_remove_dir ] ; then
    . /usr/local/f-secure/bin/safer_remove_dir
else
    echo "Warning: safer_remove_dir not found, using built-in fallback" >&2
    echo "Warning: safer_remove_dir not found, using built-in fallback" >> "$MSGLOG"
    safer_rmrf() {
	rm -rf "$@"
    }
fi

orspclient=false
if [ -d /usr/local/f-secure/orspclient ] ; then
    orspclient=true
fi

if ! $PARTIAL ; then
    # restore parent control settings to default / previously set by the user
    /usr/local/f-secure/bin/parentalcontroltool --restoreall
fi

# Disable firewall if we are controlling firewall
sudo /usr/local/f-secure/bin/should_disable_firewall && sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off

# Remove any old flag files indicating previous Browser extension uninstalls
rm -f /tmp/.com.f-secure.fsmac.uninstalled-*-extension

if ! $PARTIAL ; then
    rm -f /tmp/.fsmac.post-install-alf-suppress
    rm -f /tmp/.fs-bwuser
    rm -f /tmp/fsmac_failed_keycode
    rm -rf /tmp/.com.f-secure.fsmac.customizations*
    rm -f /tmp/.fsmac-prefpane-opened
    rm -rf /tmp/.com.f-secure.fsmac.postinstall.relaunch
fi

rm -f /tmp/.fsav.postflight-completed

# This is the old uninstall trigger which is no longer needed.
launchctl remove com.f-secure.fsmac.uninstall
rm -f /Library/LaunchDaemons/com.f-secure.fsmacuninstall.plist
rm -f /var/db/.com.f-secure.fsmac.uninstall

check_error() {
    if test $? -ne 0 ; then
	ERROR=true
	echo "ERROR: $@" >> "$MSGLOG"
    fi
}

fatalexit() {
    fatalerrormessage="$1"
    fatalerrorexitcode="$2"
    if [ -z "$fatalerrorexitcode" ] ; then
        fatalerrorexitcode=1
    fi

    {
	echo
	echo "Uninstallation failed!"
	echo "Please contact support and email them the uninstall log file:"
	echo "$LOG"
    } >> "$MSGLOG"
    syslog -s -l Critical "Uninstallation failed with error: ${fatalerrormessage}! Please contact support and email them the uninstall log file: $LOG"
    exit $fatalerrorexitcode
}

####
#
# Main()
#
date "+%Y-%m-%d %H:%M:%S Uninstalling FS Mac:"

if [ "`id -u`" != "0" ] ; then
    echo "Need root permissions to perform uninstallation. Run the command as" >> "$MSGLOG"
    echo "sudo $0" >> "$MSGLOG"
    exit 1
fi
date "+%Y-%m-%d %H:%M:%S checkpoint 1"
echo "Uninstalling..." >> "$MSGLOG"

id -a

#XFENCE Uninstaller

unloadxfence=false
if [ -f "/Library/F-Secure/XFENCE/uninstall.sh" ] ; then
    if $PARTIAL ; then
        /Library/F-Secure/XFENCE/uninstall.sh -u >>"$MSGLOG"
    else
        /Library/F-Secure/XFENCE/uninstall.sh >>"$MSGLOG"
    fi
    if [ "$?" -eq "1" ]; then
        date "+%Y-%m-%d %H:%M:%S Uninstallation failed. Can not uninstall XFENCE first"
        fatalexit "Failed to uninstall XFENCE" 2
    fi
    unloadxfence=true
fi

# Browsing Protection Extension Uninstaller - Start

if [ -d "/usr/local/f-secure/browsingprotection" ] && ! ${PARTIAL} ; then

    rm -f /tmp/.com.f-secure.fsmac.*-running

    date "+%Y-%m-%d %H:%M:%S removing browser extensions"

    if [ -d "/usr/local/f-secure/browsingprotection/chrome" ] ; then
        date "+%Y-%m-%d %H:%M:%S Triggering to uninstall Chrome Extension "
        sudo touch /tmp/.com.f-secure.fsav/uninstall
        chromeuninstallsignal="/tmp/.fs-chrome-extension-uninstall-completed-*"
        # 10 seconds time out for the use case of if user has deleted or disabled chrome extension
        timeout=$(( `date +%s` + 10 ))
        while [ `date +%s` -lt $timeout ] && [ -z "`ls $chromeuninstallsignal`" ] ; do
            echo "+%Y-%m-%d %H:%M:%S Chrome extension is not uninstalled yet, waiting for uninstall complete signal"
            sleep 1
        done
        rm -fv /Library/Google/Chrome/NativeMessagingHosts/com.fsecure.browsingprotection*bootstrap.json
        safer_rmrf /tmp/.fs-chrome-extension-uninstall-*
    else
        date "+%Y-%m-%d %H:%M:%S no Chrome browsing protection package installed - not removing Chrome browser extensions"
    fi
    # uninstalling of firefox is by default handled by chrome uninstall as now chrome and firefox addon share same code:
    if [ -d "/usr/local/f-secure/browsingprotection/firefox" ] ; then
        date "+%Y-%m-%d %H:%M:%S Removing installed firefox Extension bootstrap json file"
        rm -fv /Library/Application\ Support/Mozilla/NativeMessagingHosts/com.fsecure.browsingprotectionbootstrap.json
    else
        date "+%Y-%m-%d %H:%M:%S no firefox browsing protection package installed - not removing firefox browser bootstrap file"
    fi

    echo "Removing Safari extension for all users" >> "$MSGLOG"
    safaribundleid=com.f-secure.browsing-protection
    ecount=0
    dscl . -list /Users NFSHomeDirectory|awk '{print $NF}' | sort | uniq | while read homedir;do
      for safariext in "${homedir}"/Library/Safari/Extensions/*.safariextz ; do
          if [ -d "${homedir}"/Library/Safari/Extensions ];then
              tempdir=`mktemp -d -t safariextension-uninstaller`
              xar -C $tempdir -xvf "$safariext" 'Info.plist$'
              theirid=$(/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" $tempdir/*/Info.plist)
              date "+%Y-%m-%d %H:%M:%S Examining Safari extension $safariext with bundle ID $theirid"
              if [ "$safaribundleid" = "$theirid" ]; then
                  date "+%Y-%m-%d %H:%M:%S removing $safariext"
                  safer_rmrf "$safariext"
                  ecount=$(( $ecount + 1 ))
                  touch /tmp/.com.f-secure.fsmac.uninstalled-safari-extension
              else
                  date "+%Y-%m-%d %H:%M:%S bundle ID mismatch - not removing $safariext"
              fi
          fi
      done
    done
else
    date "+%Y-%m-%d %H:%M:%S upgrade or no browsing protection package installed - not removing browser extensions"
fi

#Browsing Protection Extensions Uninstaller - End

# Remove Google Chrome Browsing Protection Extension if installed
if [ -d "/usr/local/f-secure/browsingprotection/chrome" ] ; then
    date "+%Y-%m-%d %H:%M:%S removing chrome browser extensions"
    echo "Removing chrome extension for all users" >> "$MSGLOG"

    # Removing crx file from Chrome User Extension Folder
    chrome_external_extensions_dir_user="Library/Application Support/Google/Chrome/External Extensions"

    dscl . -list /Users NFSHomeDirectory|awk '{print $NF}' | sort | uniq | while read homedir ; do
      date "+%Y-%m-%d %H:%M:%S Deleting Chrome extension symlink for ${homedir}"
      chrome_extension_fullpath_user="${homedir}"/"${chrome_external_extensions_dir_user}"

      ls "$chrome_extension_fullpath_user" | grep -e "fcmmbkhhogkhbpijkidmocpcomnmpgif" -e "ceccehjjnpkifbmecpnmnfkkjbdknjnn" -e "idpkgibhbjmogkfbkmjnnkhpgdagoeme" | while read chrome_extension_id ; do
        chrome_extension_crx_user="$chrome_extension_fullpath_user"/"$chrome_extension_id"
          if [ -f "$chrome_extension_crx_user" ] ; then
              date "+%Y-%m-%d %H:%M:%S Deleting Chrome add-on symlink ${chrome_extension_crx_user}"
              rm -f "$chrome_extension_crx_user"
              touch /tmp/.com.f-secure.fsmac.uninstalled-chrome-extension-"${chrome_extension_id}"
          fi
      done
    done

    # Removing crx file from Chrome Global Extension Folder
    chrome_external_extensions_dir_global="/Library/Application Support/Google/Chrome/External Extensions"
    ls "$chrome_external_extensions_dir_global" | grep -e "fcmmbkhhogkhbpijkidmocpcomnmpgif" -e "ceccehjjnpkifbmecpnmnfkkjbdknjnn" -e "idpkgibhbjmogkfbkmjnnkhpgdagoeme" | while read chrome_extension_id ; do
        chrome_extension_fullpath_global="$chrome_external_extensions_dir_global"/"$chrome_extension_id"

        if [ -f "$chrome_extension_fullpath_global" ] ; then
            date "+%Y-%m-%d %H:%M:%S Deleting Chrome add-on from Chrome Global Extension Folder ${chrome_extension_fullpath_global}"
            rm -f "$chrome_extension_fullpath_global"
            touch /tmp/.com.f-secure.fsmac.uninstalled-chrome-extension-"${chrome_extension_id}"-global-folder
        fi
    done

else
    date "+%Y-%m-%d %H:%M:%S no browsing protection package installed - not removing firefox browser extensions"
fi
# Remove Google Chrome Browsing Protection Extension - End

# Remove Firefox Browsing Protection Extension if installed
if [ -d "/usr/local/f-secure/browsingprotection/firefox" ] ; then
    date "+%Y-%m-%d %H:%M:%S removing firefox browser extensions"
    echo "Removing firefox extension for all users" >> "$MSGLOG"

    firefox_application_id="{ec8030f7-c20a-464f-9b0e-13a3a9e97384}"
    firefox_user_extensions_folder="Library/Application Support/Mozilla/Extensions/${firefox_application_id}"

    dscl . -list /Users NFSHomeDirectory|awk '{print $NF}' | sort | uniq | while read homedir ; do
        date "+%Y-%m-%d %H:%M:%S Deleting Firefox extension xpi for ${homedir}"
        firefox_fullpath_user="${homedir}"/"${firefox_user_extensions_folder}"

        ls "$firefox_fullpath_user" | grep "@f-secure.com" | while read firefox_extension_xpi_file ; do
            firefox_extension_xpi_user="$firefox_fullpath_user"/"$firefox_extension_xpi_file"
            if [ -f "$firefox_extension_xpi_user" ] ; then
                date "+%Y-%m-%d %H:%M:%S Deleting Firefox add-on ${firefox_extension_xpi_user}"
                rm -f "$firefox_extension_xpi_user"
                touch /tmp/.com.f-secure.fsmac.uninstalled-firefox-extension-"${firefox_extension_xpi_file}"
            fi
        done
    done

    # Removing xpi file from Firefox Global Extension Folder
    firefox_global_extensions_folder="/Library/Application Support/Mozilla/Extensions/${firefox_application_id}"
    ls "$firefox_global_extensions_folder" | grep "@f-secure.com" | while read firefox_extension_xpi_file ; do
        firefox_extension_fullpath_global="$firefox_global_extensions_folder"/"$firefox_extension_xpi_file"
        if [ -f "$firefox_extension_fullpath_global" ] ; then
            date "+%Y-%m-%d %H:%M:%S Deleting Firefox add-on from Firefox Global Extension Folder ${firefox_extension_fullpath_global}"
            rm -f "$firefox_extension_fullpath_global"
            touch /tmp/.com.f-secure.fsmac.uninstalled-firefox-extension-"${firefox_extension_xpi_file}"-global-folder
        fi
    done

else
    date "+%Y-%m-%d %H:%M:%S no browsing protection package installed - not removing firefox browser extensions"
fi
# Remove Firefox Browsing Protection Extension - End

ERROR=false

ps axo "user,pid,uid,gid,comm" |
	awk '$1 != "root" && /loginwindow/ {printf "user=%s pid=%s userid=%s groupid=%s\n", $1, $2, $3, $4}' |
		while read e ; do
		    eval $e
                        if $unloadxfence ; then
			    errors=`launchctl asuser $userid chroot -u $userid -g $groupid / launchctl unload -S Aqua /Library/LaunchAgents/com.fsecure.XFENCEUserAgent.plist 2>&1`
			    if [ -n "$errors" ]; then
			        echo "$errors"
			        echo "Unloading launch agents is not fatal, continuing..."
			    fi
                        fi

			errors=`launchctl asuser $userid chroot -u $userid -g $groupid / launchctl unload -S Aqua /Library/LaunchAgents/com.f-secure.fsmac.gui.plist 2>&1`
			if [ -n "$errors" ]; then
			    echo "$errors"
			    echo "Unloading launch agents is not fatal, continuing..."
			fi
			errors=`launchctl asuser $userid chroot -u $userid -g $groupid / launchctl unload /Library/LaunchAgents/com.f-secure.trasher.plist 2>&1`
			if [ -n "$errors" ]; then
			    echo "$errors"
			    echo "Unloading launch agents is not fatal, continuing..."
			fi
                        if [ -f /Library/LaunchAgents/com.f-secure.fsbpserver.plist ] ; then
			    errors=`launchctl asuser $userid chroot -u $userid -g $groupid / launchctl unload /Library/LaunchAgents/com.f-secure.fsbpserver.plist 2>&1`
			    if [ -n "$errors" ]; then
			        echo "$errors"
			        echo "Unloading launch agents is not fatal, continuing..."
			    fi
                        fi
			if ! $PARTIAL ; then
			    errors=`launchctl asuser $userid chroot -u $userid -g $groupid / launchctl unload /Library/LaunchAgents/com.f-secure.relauncher.plist 2>&1`
			    if [ -n "$errors" ]; then
				echo "$errors"
				echo "Unloading launch agents is not fatal, continuing..."
			    fi
			fi
                        errors=`launchctl asuser $userid chroot -u $userid -g $groupid / launchctl remove com.f-secure.fsmac.subsvars 2>&1`
                        if [ -n "$errors" ]; then
                            echo "$errors"
                            echo "Unloading old launch agent (subsvars) is not fatal, continuing..."
                        fi
		done
check_error "Failed to unload GUI"
date "+%Y-%m-%d %H:%M:%S checkpoint 2"
echo "LaunchAgents unloaded" >> "$MSGLOG"

processes_to_kill[0]=fscuif
processes_to_kill[1]="F-Secure Mac Protection"
processes_to_kill[2]="Safe Anywhere Mac Main Window"
for n in 0 1 2; do
    procname="${processes_to_kill[$n]}"
    if ! killall -0 "$procname" 2> /dev/null; then
        continue
    fi
    if killall "$procname"; then
        sleep 2
        if killall -0 "$procname" ; then
	    killall -9 "$procname"
        fi
    fi
done
date "+%Y-%m-%d %H:%M:%S checkpoint 3"
echo "GUI killed" >> "$MSGLOG"

/bin/rm -f "/Library/LaunchAgents/com.f-secure.fsmac.gui.plist"
rm -f /Library/LaunchAgents/com.f-secure.fsmac.subsvars.plist
/bin/rm -f "/Library/LaunchAgents/com.f-secure.trasher.plist"
/bin/rm -f "/Library/LaunchAgents/com.f-secure.fsbpserver.plist"
/bin/rm -f "/Library/Preferences/com.f-secure.fsmac.gui.plist"
if $unloadxfence ; then
    /bin/rm -f /Library/LaunchAgents/com.fsecure.XFENCEUserAgent.plist
fi
if ! $PARTIAL ; then
    /bin/rm -f "/Library/LaunchAgents/com.f-secure.relauncher.plist"
fi

# NOTE: uninstall is not listed in labels because if we unloaded it
# launchd would kill this script
daemon_labels="com.f-secure.fsavd.dbver_update \
com.f-secure.clstate-dbupdate \
com.f-secure.clstate-periodic \
com.f-secure.fsmac.fsupdated \
com.f-secure.fsmac.fsupdated_guts2 \
com.f-secure.fsavd.dbhelper \
com.f-secure.fsavd \
com.f-secure.fsmac.licensetool \
com.f-secure.fsmac.guts2downloader \
com.f-secure.fscsafesettingsd \
com.f-secure.urlexceptiond \
com.f-secure.fscsafeadmind \
com.f-secure.uplinkdaemon \
com.f-secure.fsctelemetryd"

daemon_plists="com.f-secure.fsavd.dbver_update.plist \
com.f-secure.clstate-dbupdate.plist \
com.f-secure.clstate-periodic.plist \
com.f-secure.fsmac.fsupdated.plist \
com.f-secure.fsmac.fsupdated_guts2.plist \
com.f-secure.fsavd.dbhelper.plist \
com.f-secure.fsavd.plist \
com.f-secure.fsmacuninstall.plist \
com.f-secure.fsmac.licensetool.plist \
com.f-secure.fsmac.guts2downloader.plist \
com.f-secure.fscsafesettingsd.plist \
com.f-secure.urlexceptiond.plist \
com.f-secure.fscsafeadmind.plist \
com.f-secure.uplinkdaemon.plist \
com.f-secure.fsctelemetryd.plist"

orspplist=com.f-secure.orspclient.plist
if [ -f "/Library/LaunchDaemons/$orspplist" ] ; then
    daemon_labels="$daemon_labels com.f-secure.orspclient"
    daemon_plists="$daemon_plists $orspplist"
fi

for daemon in $daemon_labels; do
    echo "Stopping $daemon"
    launchctl remove $daemon
done

for plist in $daemon_plists; do
    rm -f /Library/LaunchDaemons/$plist
done

date "+%Y-%m-%d %H:%M:%S checkpoint 4"
echo "LaunchDaemons unloaded" >> "$MSGLOG"

if ! $PARTIAL ; then
    root_defaults=( com.f-secure.fscsafeadmind )
    # PSB stores CCR token in uplinkdaemon's user defaults, and FSKit (used by uplinkdaemon) stores subscription info
    if [ -x /usr/local/f-secure/bin/uplinkdaemon ] && [ -f /Library/F-Secure/fsmac/config/dis_server ] ; then
        root_defaults+=( com.f-secure.uplinkdaemon )
        root_defaults+=( uplinkdaemon )
    fi
    for domain in "${root_defaults[@]}"; do
        defaults delete $domain
    done
    # PSB SPI doesn't support subscription release
    if ! [ -f /Library/F-Secure/fsmac/config/always_tokensignup ] ; then
        echo "Releasing subcription" >> "$MSGLOG"
        /usr/local/f-secure/fssp/bin/licensetool --release-me
    fi
fi

if [ -f /usr/local/f-secure-rdr/bin/uninstall ] ; then
    echo "Removing RDR" >> "$MSGLOG"
    /usr/local/f-secure-rdr/bin/uninstall
fi

rm -rf "/Library/PreferencePanes/Safe Anywhere Mac Settings.prefPane"

# Remove infections.db for all users
/bin/rm -f /Users/*/Library/Application\ Support/F-Secure/Mac\ Protection/infections.db
/bin/rm -f /tmp/infections_[0-9][0-9]*.db /tmp/.com.f-secure.fsav/infections.db*
# Remove F-Secure directories, only if they're empty
/bin/rmdir /Users/*/Library/Application\ Support/F-Secure/Mac\ Protection
/bin/rmdir /Users/*/Library/Application\ Support/F-Secure

# For all non-system users, delete any defaults domain we may have created
# Do it with the "defaults" command to make sure the change is visible to all
dscl . list /Users uid | while read username uid ; do
    if [ "$uid" -ge 500 ] ; then
        if ! $PARTIAL ; then
            prefdomains="com.f-secure.fsmac.gui com.f-secure.F-Secure+ControlLayer-$uid com.f-secure.Safe-Anywhere-Mac-Settings com.f-secure.fsmac.gui-main-window"
            for domain in $prefdomains; do
                domain=`echo "$domain" | sed -e 's/\+/ /g'` # to handle domains with spaces
                date "+%Y-%m-%d %H:%M:%S Deleting defaults domain $domain for user $username ($uid)"
                sudo -u "$username" defaults delete "$domain"
            done
        fi
    fi
done
date "+%Y-%m-%d %H:%M:%S checkpoint 5"
echo "Removing in /Applications" >> "$MSGLOG"

remove_app() {
    app="$1"
    bundleid="$2"
    find /Applications -maxdepth 2 -type d -name "$app" | while read app_path; do
	if [ -z "$app_path" ]; then
	    echo "$app was not found. Maybe someone (re)moved it?" >> "$MSGLOG"
	    continue
	fi
	if grep "<string>${bundleid}</string>" "${app_path}/Contents/Info.plist"; then
	    :
	else
	    echo "$app_path found, but bundle id does not match $bundleid" >> "$MSGLOG"
	    continue
	fi
	if [ "$app_path" = "/Applications" -o "$app_path" = "/" ]; then
	    echo "Something is wrong! Installation folder was detected as $app_path" >> "$MSGLOG"
	else
	    safer_rmrf "$app_path"
	fi
	app_parent=`dirname "$app_path"`
	if [ "$app_parent" = "/Applications" -o "$app_parent" = "/" ]; then
	    echo "app parent dir $app_parent, not removing" >> "$MSGLOG"
	else
	    rmdir "$app_parent"
	fi
    done
}

remove_app 'F-Secure Mac Protection.app' 'com.f-secure.fsmac.gui'
remove_app 'Support Tool.app' 'com.f-secure.fsmac.fsdiag'
remove_app 'uninstall.app' 'com.f-secure.fsmac.gui.uninstall'

date "+%Y-%m-%d %H:%M:%S checkpoint 6"
echo "Removing daemons and command line tools" >> "$MSGLOG"

filelist=`mktemp -t .com.f-secure.uninstall.filelist`
cat<<EOF> $filelist
com.f-secure.agents-and-daemons /Library
com.f-secure.fsmac.bin /usr/local/f-secure/bin
com.f-secure.fsmac.customization /Library/F-Secure/fsmac
com.f-secure.fsmac.fsauth /System/Library/Extensions
com.f-secure.fsmac.gui.customization /Library/F-Secure/fsmac/app
com.f-secure.fsmac.lib /usr/local/f-secure/lib
EOF

## if ORSP
cat <<EOF >> $filelist
com.f-secure.fsmac.orspclient /usr/local/f-secure/orspclient
EOF


if ${PARTIAL} ; then
    /bin/sh -c '/usr/bin/find -d /usr/local/f-secure/ -type f -or -type l |  /usr/bin/grep -v '\''fssp/var/auth/test\|fsmac/SECL\|fsmac/sysconfig\|fsmac/substatus\|var/fsctelemetryd'\'' | while read file ; do /bin/rm -v "$file"; done'
    /bin/sh -c '/usr/bin/find -d /usr/local/f-secure/ -type d | while read dir ; do /bin/rmdir "$dir"; done'
else
    safer_rmrf "/usr/local/f-secure/"
    dscl . -delete /Groups/fsc
fi

/bin/rm -f /usr/local/bin/dbupdate /usr/local/bin/fsav


date "+%Y-%m-%d %H:%M:%S checkpoint 7"
echo "Removing driver" >> "$MSGLOG"

waiting=10
while killall -0 fsavd && [ $waiting -gt 0 ]; do
    echo "fsavd still running, waiting for it to exit"
    sleep 1
    waiting=`expr $waiting - 1`
done
if killall -0 fsavd; then
    echo "fsavd is still running, falling back to kill -9"
    killall -9 fsavd
    sleep 1
fi

remove_kext() {
    kextBundleId=$1
    kextBundleName=$2
    required=$3

    if kextstat -b $kextBundleId | grep -q $kextBundleId; then
        kextunloaded=false
        for attempt in 1 2 3 4; do
            if ! kextunload -b $kextBundleId ; then
                echo "Failed to unload $kextBundleId, retrying in a few seconds (attempt: $attempt)"
                sleep 3
            else
                kextunloaded=true
                break
            fi
        done
        if ! $kextunloaded ; then
            if [ "$required" == "true" ] ; then
                echo "ERROR: Failed to remove kernel extension $kextBundleId" >> "$MSGLOG"
                ERROR=true
            else
                echo "WARNING: Failed to remove kernel extension $kextBundleId, will continue" >> "$MSGLOG"
            fi
        fi
    fi
    safer_rmrf "/System/Library/Extensions/$kextBundleName"
    safer_rmrf "/Library/Extensions/$kextBundleName"
}

remove_kext com.f-secure.kext.fsauth fsauth.kext true
remove_kext com.f-secure.kext.nke fsnke.kext false # fsnke may fail to unload if already binded to sockets (almost every time)
safer_rmrf "/Library/F-Secure/LegacyExtensions"

if $NUKE_CUSTOMIZATIONS ; then
    echo "Removing customizations" >> "$MSGLOG"

    safer_rmrf "/Library/F-Secure/fsmac"

    ${PKGUTIL} --pkgs | grep ^com.f-secure.fsmac | grep customiz | xargs -n 1 ${PKGUTIL} --forget
    ls -d /Library/Receipts/com.f-secure.fsmac* | grep customiz | xargs rm -rf
fi

date "+%Y-%m-%d %H:%M:%S checkpoint 8"
echo "Removing receipts" >> "$MSGLOG"
echo `${PKGUTIL} --pkgs | grep ^com.f-secure.fsmac | grep -v customiz` com.f-secure.fssp.pkg com.f-secure.fssp com.f-secure.agents-and-daemons.pkg com.f-secure.agents-and-daemons | xargs -n 1 ${PKGUTIL} --forget
if $unloadxfence ; then
    ${PKGUTIL} --forget com.f-secure.xfence
fi
if $orspclient ; then
    ${PKGUTIL} --forget com.f-secure.orspclient
    ${PKGUTIL} --forget com.f-secure.browsingprotection
fi

ls -d /Library/Receipts/com.f-secure.fsmac* | grep -v customiz | xargs rm -rf
rm -rf /Library/Receipts/com.f-secure.fssp.*
rm -rf /Library/Receipts/com.f-secure.fsauth.*
rm -rf /Library/Receipts/com.f-secure.fsnke.*

rm -rf /tmp/.com.f-secure.fsav
rm -f /tmp/ods-*.db
rm -f /tmp/ods-*.db.real
rm -f /Users/*/Library/Application\ Support/F-Secure/Mac\ Protection/infections.db
rm -f /var/log/fsavd.log
rm -rf /Library/Caches/com.f-secure.MacProtection.*
rm -f "/Library/Application Support/F-Secure/expirytime"

echo >> "$MSGLOG"

/bin/rmdir "/Library/Application Support/F-Secure/"

if ! ${PARTIAL} ; then
    echo "Removing /Library/F-Secure/fsmac because partial=${partial}"
    safer_rmrf /Library/F-Secure/fsmac
    /bin/rmdir /Library/F-Secure # will be removed if empty
    echo "Removing SECL logs and application support files"
    rm -fv /Library/Logs/SECL.log*
    dscl . -list /Users NFSHomeDirectory|awk '{print $NF}' | sort | uniq | while read homedir; do
        for f in "${homedir}/Library/Logs/SECL.log" "${homedir}/Library/Logs/SECL.log.old" \
                 "${homedir}/Library/Application Support/F-Secure/Safe Anywhere Mac/browsing-protection-settings" \
                 "${homedir}/Library/Application Support/F-Secure/Safe Anywhere Mac/upstream.db" ; do
            if [ -f "$f" ] ; then
                echo "Deleting $f"
                rm -f "$f"
            fi
        done
        # Remove F-Secure app support directories, only if they're empty
        /bin/rmdir "${homedir}/Library/Application Support/F-Secure/Safe Anywhere Mac/"
        /bin/rmdir "${homedir}/Library/Application Support/F-Secure/"
    done
else
    echo "Not removing /Library/F-Secure/fsmac because this is an upgrade"
fi

echo "Removing Support Tool privileged helper tool"
helperToolBundleID="com.f-secure.fsmac.fsdiag.helper"
launchctl unload /Library/LaunchDaemons/$helperToolBundleID.plist
rm /Library/PrivilegedHelperTools/$helperToolBundleID
rm /Library/LaunchDaemons/$helperToolBundleID.plist

# Empty the contents of the magic file to prevent further accidental uninstalls.
echo >$MAGIC

date "+%Y-%m-%d %H:%M:%S checkpoint 9"

if $ERROR ; then
    echo "Some errors were encountered during uninstallation." >> "$MSGLOG"
    echo "Please contact support and email them the uninstall log file:"  >> "$MSGLOG"
    echo "$LOG"  >> "$MSGLOG"
    echo  >> "$MSGLOG"
    echo "Please reboot before reinstalling the product." >> "$MSGLOG"
    rc=1
else
    echo "Uninstallation complete." >> "$MSGLOG"
    syslog -s -l Critical "Uninstallation complete."
    rc=0
fi
echo $rc > /tmp/.com.f-secure.fsmac.uninstall-rc
date "+%Y-%m-%d %H:%M:%S checkpoint 10"
exit $rc
