#!/usr/bin/env bash
# ZPLServer — macOS uninstall script
# Must be run as root or with sudo.
#
# Usage:
#   sudo ./uninstall.sh               # remove service and files only
#   sudo ./uninstall.sh --remove-data # also remove settings and license data
set -euo pipefail

INSTALL_DIR="/usr/local/zplserver"
PLIST_PATH="/Library/LaunchDaemons/com.neodynamic.zplserver.plist"
LABEL="com.neodynamic.zplserver"
REMOVE_DATA=false

for arg in "$@"; do
    [[ "$arg" == "--remove-data" ]] && REMOVE_DATA=true
done

if [[ $EUID -ne 0 ]]; then
    echo "Error: this script must be run as root (use sudo)." >&2
    exit 1
fi

# --- Stop and unload service ---
if launchctl list "$LABEL" &>/dev/null; then
    echo "Stopping service..."
    launchctl stop "$LABEL" 2>/dev/null || true
    echo "Unloading service..."
    launchctl unload "$PLIST_PATH" 2>/dev/null || true
fi

# --- Remove plist ---
if [[ -f "$PLIST_PATH" ]]; then
    echo "Removing launchd plist..."
    rm "$PLIST_PATH"
fi

# --- Remove installed files ---
if [[ -d "$INSTALL_DIR" ]]; then
    echo "Removing $INSTALL_DIR ..."
    rm -rf "$INSTALL_DIR"
fi

# --- Optionally remove data ---
if $REMOVE_DATA; then
    echo "Removing settings and license data..."
    # Settings (per-user — remove for all users under /Users)
    for userHome in /Users/*; do
        rm -rf "$userHome/Library/Application Support/ZPLServer" 2>/dev/null || true
    done
    # License (system-wide)
    rm -rf "/Library/Application Support/ZPLServer" 2>/dev/null || true
fi

echo ""
echo "ZPLServer uninstalled successfully."
if ! $REMOVE_DATA; then
    echo "Note: settings and license data were kept."
    echo "      Run with --remove-data to delete them as well."
fi
