#!/bin/bash
# ==============================================================
# uninstall-vineforce-teams.sh
# Force-stops Vineforce Teams (if running) and purges the .deb
# package, so nothing is left behind and nothing keeps running.
# ==============================================================
set -uo pipefail

PKG_NAME="vineforce-teams"
APP_PATTERN="Vineforce.Admin.Desktop.Avalonia"

echo "=== Stopping Vineforce Teams if it's running ==="

if pgrep -f "$APP_PATTERN" >/dev/null 2>&1; then
    echo "Found a running instance — sending SIGTERM..."
    pkill -TERM -f "$APP_PATTERN" 2>/dev/null || true

    for i in 1 2 3 4 5; do
        if ! pgrep -f "$APP_PATTERN" >/dev/null 2>&1; then
            echo "Process exited cleanly."
            break
        fi
        sleep 1
    done

    if pgrep -f "$APP_PATTERN" >/dev/null 2>&1; then
        echo "Still running after 5s — sending SIGKILL..."
        pkill -KILL -f "$APP_PATTERN" 2>/dev/null || true
        sleep 1
    fi
else
    echo "No running instance found."
fi

echo ""
echo "=== Purging the package ==="

PKG_STATUS="$(dpkg-query -W -f='${Status}' "$PKG_NAME" 2>/dev/null || true)"

if echo "$PKG_STATUS" | grep -q "install ok installed"; then
    sudo apt purge -y "$PKG_NAME"
else
    echo "Package '$PKG_NAME' is not currently installed via apt/dpkg."
fi

echo ""
echo "=== Verifying removal ==="

if pgrep -f "$APP_PATTERN" >/dev/null 2>&1; then
    echo "WARNING: a process matching '$APP_PATTERN' is still running."
    echo "Check manually with: ps aux | grep -i vineforce"
else
    echo "No Vineforce Teams process is running."
fi

if [ -d "/opt/${PKG_NAME}" ]; then
    echo "WARNING: /opt/${PKG_NAME} still exists."
else
    echo "Application folder removed."
fi

echo ""
echo "=== UNINSTALL COMPLETE ==="
