#!/bin/bash
#
# Forcepoint DSE Agent Uninstall Script
# -------------------------------------
# Purpose : Uninstall the Forcepoint DSE Agent on macOS.
# Version : v1 - Initial script for version 30.8.136
#
# Notes:
#   - Must be run as root (sudo).
#   - The release code below is required by wepsvc to authorize the uninstall.
#
# Usage:
#   sudo ./uninstall_dse_agent.sh
#
# --- Configuration -----------------------------------------------------------
APP_PATH="/Applications/Forcepoint DLP Endpoint.app"
INFO_PLIST="${APP_PATH}/Contents/Info.plist"
WEPSVC="/usr/local/sbin/wepsvc"
LOG_FILE="/var/log/DSEAgentUninstall.log"
# Please update the Release code from Data Security Portal. This used by wepsvc to authorize the uninstall.
RELEASE_CODE="releasecode"
# Which version(s) to uninstall.
#   Option 1 - Specific versions: list one or more exact versions. The agent
#              is removed only if the installed version matches one of them.
#              e.g. TARGET_VERSIONS=("30.8.117" "30.8.120")
#   Option 2 - Any version: set to ("any") to uninstall whatever is installed
#              regardless of version.
TARGET_VERSIONS=("any")
# --- Helpers -----------------------------------------------------------------
# log <message> : write a timestamped line to both stdout and the log file.
log() {
    local message="$1"
    local timestamp
    timestamp="$(date '+%Y-%m-%d %H:%M:%S')"
    echo "${timestamp} - ${message}" | tee -a "${LOG_FILE}"
}
# version_targeted <installed_version> : return 0 if the installed version
# should be uninstalled, 1 otherwise. Matches when TARGET_VERSIONS contains
# "any" or contains the exact installed version.
version_targeted() {
    local installed="$1"
    local target
    for target in "${TARGET_VERSIONS[@]}"; do
        if [ "${target}" = "any" ] || [ "${target}" = "${installed}" ]; then
            return 0
        fi
    done
    return 1
}
# --- Pre-flight checks --------------------------------------------------------
# Require root privileges.
if [ "${EUID}" -ne 0 ]; then
    echo "Please run as root (e.g. sudo $0)."
    exit 1
fi
# Log runtime context. This helps diagnose "works in Terminal, fails in Jamf"
# cases: whoami should be root either way, but console_user shows whether a
# user is actually logged into the GUI when the policy runs (Jamf daemons
# often run with no active session).
console_user="$(/usr/bin/stat -f%Su /dev/console 2>/dev/null)"
log "Run context: user=$(/usr/bin/whoami), console_user=${console_user:-none}, tty=$(/usr/bin/tty 2>/dev/null || echo none)"
# Confirm the agent is actually installed before attempting anything.
if [ ! -d "${APP_PATH}" ]; then
    log "Forcepoint DSE Agent is not installed. Nothing to do."
    exit 0
fi
# --- Determine installed version ---------------------------------------------
# Read the installed version for logging. Fall back to "unknown" if it can't
# be read so the log lines stay meaningful.
app_version="$(/usr/bin/defaults read "${INFO_PLIST}" CFBundleShortVersionString 2>/dev/null)"
if [ -z "${app_version}" ]; then
    app_version="unknown"
fi
log "Found Forcepoint DSE Agent version ${app_version}."
# Skip machines whose version isn't targeted (unless TARGET_VERSIONS is "any").
if ! version_targeted "${app_version}"; then
    log "Version ${app_version} is not in the target list (${TARGET_VERSIONS[*]}). Skipping."
    exit 0
fi
log "Version ${app_version} is targeted. Starting uninstall."
# --- Uninstall ----------------------------------------------------------------
# Wait 30 seconds before triggering the uninstall.
log "Waiting 30 seconds before uninstall..."
sleep 30
# Perform the uninstallation. The release code is passed to wepsvc via
# --password to authorize removal. Capture wepsvc's own stdout/stderr and
# exit code so the exact reason for any failure is recorded in the log
# (useful when the same command works in Terminal but fails under Jamf).
uninstall_output="$(sudo "${WEPSVC}" --uninstall --password ${RELEASE_CODE} 2>&1)"
uninstall_rc=$?

# Record whatever wepsvc printed, line by line, into the log.
if [ -n "${uninstall_output}" ]; then
    while IFS= read -r line; do
        log "wepsvc: ${line}"
    done <<< "${uninstall_output}"
fi

if [ "${uninstall_rc}" -eq 0 ]; then
    log "Successfully uninstalled Forcepoint DSE Agent version ${app_version}."
else
    log "Failed to uninstall Forcepoint DSE Agent version ${app_version} (wepsvc exit code ${uninstall_rc})."
    exit 1
fi
# --- User notification --------------------------------------------------------
# Notify the logged-in user that the uninstall completed.
osascript -e 'display dialog "Forcepoint DSE Agent was uninstalled successfully" buttons {"OK"} default button "OK" with title "Uninstall"'
exit 0