#!/bin/bash
# uninstall_meshcentral.sh
# Full uninstall del agente MeshCentral en macOS (ZH Consultores)
# Limpia: daemons, plists, install dir, .db con cert, logs, residuos en /tmp
#
# Usage:
#   bash uninstall_meshcentral.sh
#   bash <(curl -fsSL https://zh.com.pa/mcuninstall)
#
# Despues de correr esto, podes reinstalar limpio con:
#   bash <(curl -fsSL https://zh.com.pa/mcimac)

set -u

# ============================================
# COLORES
# ============================================
CYAN='\033[0;36m'; GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[1;33m'; WHITE='\033[0;37m'; NC='\033[0m'

# Constantes
SERVICENAME="ZH_Consultores_Remote_Agent"
INSTALL_PARENT="/usr/local/mesh_services"

clear
echo -e "\n${CYAN}========================================${NC}"
echo -e "${CYAN}  MeshCentral Agent FULL UNINSTALL - ZH${NC}"
echo -e "${CYAN}========================================${NC}\n"

[[ "$(uname)" != "Darwin" ]] && { echo -e "${RED}ERROR: Solo macOS.${NC}"; exit 1; }

# Forzar TTY (cuando corre via pipe)
if [[ ! -t 0 ]]; then
    if [[ -e /dev/tty ]]; then exec < /dev/tty
    else echo -e "${RED}ERROR: No hay terminal interactiva.${NC}"; exit 1; fi
fi

# Confirmacion
echo -e "${YELLOW}Esto eliminara:${NC}"
echo "  - Servicios ${SERVICENAME} (daemon + KVM agent) y variantes meshagent"
echo "  - ${INSTALL_PARENT} (binario, .msh, .db con cert)"
echo "  - /Library/Launch{Daemons,Agents}/${SERVICENAME}.plist + meshagent.plist"
echo "  - /var/log/${SERVICENAME}.{log,err}"
echo "  - Residuos en /tmp/meshagent*, /tmp/ZH_MeshAgent_*"
echo ""
echo -e "${WHITE}NOTA: el nodo seguira existiendo en MeshCentral como 'offline'.${NC}"
echo -e "${WHITE}Para borrarlo, hacer click derecho sobre el nodo en el UI -> Delete Device.${NC}"
echo ""
read -r -p "Proceder? (S/N): " confirm
[[ ! "$confirm" =~ ^[YySs] ]] && { echo -e "\n${YELLOW}Cancelado.${NC}\n"; exit 0; }

# ============================================
# Sudo
# ============================================
echo -e "\n${YELLOW}Solicitando privilegios admin...${NC}"
echo -n "Password: "
read -r -s password; echo ""
if ! echo "$password" | sudo -S -v 2>/dev/null; then
    echo -e "${RED}ERROR: contrasena incorrecta.${NC}"; unset password; exit 1
fi
unset password

# ============================================
# 1. Detener servicios (todas las variantes de label)
# ============================================
echo -e "\n${YELLOW}[1/7] Deteniendo servicios launchd...${NC}"
sudo launchctl bootout "system/${SERVICENAME}"                              2>/dev/null || true
sudo launchctl bootout "gui/$(id -u)/${SERVICENAME}-launchagent"            2>/dev/null || true
sudo launchctl bootout "system/meshagent"                                   2>/dev/null || true
sudo launchctl bootout "gui/$(id -u)/meshagent-launchagent"                 2>/dev/null || true
sudo launchctl bootout "gui/$(id -u)/meshagent"                             2>/dev/null || true
echo -e "${GREEN}  OK${NC}"

# ============================================
# 2. Matar procesos colgados
# ============================================
echo -e "\n${YELLOW}[2/7] Matando procesos residuales...${NC}"
sudo pkill -9 -f "${SERVICENAME}"  2>/dev/null || true
sudo pkill -9 -x meshagent         2>/dev/null || true
sleep 2
REMAINING=$(ps aux | grep -iE "${SERVICENAME}|^[^[:space:]]+[[:space:]]+[0-9]+.*meshagent" | grep -v grep | grep -v "Microsoft Teams" || true)
if [[ -n "$REMAINING" ]]; then
    echo -e "${RED}  AVISO: procesos persisten:${NC}"
    echo "$REMAINING"
else
    echo -e "${GREEN}  OK${NC}"
fi

# ============================================
# 3. Eliminar plists
# ============================================
echo -e "\n${YELLOW}[3/7] Eliminando plists...${NC}"
for plist in \
    "/Library/LaunchDaemons/${SERVICENAME}.plist" \
    "/Library/LaunchAgents/${SERVICENAME}.plist" \
    "/Library/LaunchDaemons/meshagent.plist" \
    "/Library/LaunchAgents/meshagent.plist"; do
    if sudo test -e "$plist"; then
        sudo rm -f "$plist" && echo "  ${plist}"
    fi
done
echo -e "${GREEN}  OK${NC}"

# ============================================
# 4. Eliminar directorio de instalacion
# ============================================
echo -e "\n${YELLOW}[4/7] Eliminando ${INSTALL_PARENT}...${NC}"
if sudo test -d "$INSTALL_PARENT"; then
    sudo rm -rf "$INSTALL_PARENT"
    echo -e "${GREEN}  OK${NC}"
else
    echo -e "${WHITE}  (no existe, nada que borrar)${NC}"
fi

# ============================================
# 5. Eliminar logs
# ============================================
echo -e "\n${YELLOW}[5/7] Eliminando logs...${NC}"
sudo rm -f "/var/log/${SERVICENAME}.log" "/var/log/${SERVICENAME}.err"
echo -e "${GREEN}  OK${NC}"

# ============================================
# 6. Limpiar residuos /tmp
# ============================================
echo -e "\n${YELLOW}[6/7] Limpiando residuos en /tmp...${NC}"
sudo rm -f /tmp/meshagent /tmp/meshagent.db /tmp/meshagent-kvm-*.sock 2>/dev/null
sudo rm -f /tmp/ZH_MeshAgent_* /tmp/ZH_MeshInstaller_* 2>/dev/null
echo -e "${GREEN}  OK${NC}"

# ============================================
# 7. Verificacion final
# ============================================
echo -e "\n${YELLOW}[7/7] Verificacion final...${NC}"
ALL_CLEAN=true

PROCS=$(ps aux | grep -iE "${SERVICENAME}|meshagent" | grep -v grep | grep -v "Microsoft Teams" || true)
if [[ -n "$PROCS" ]]; then
    echo -e "${RED}  X procesos aun corriendo:${NC}"
    echo "$PROCS"
    ALL_CLEAN=false
else
    echo -e "${GREEN}  OK procesos: ninguno${NC}"
fi

if sudo test -d "$INSTALL_PARENT"; then
    echo -e "${RED}  X ${INSTALL_PARENT} aun existe${NC}"
    ALL_CLEAN=false
else
    echo -e "${GREEN}  OK ${INSTALL_PARENT}: no existe${NC}"
fi

PLISTS=$(sudo ls /Library/LaunchDaemons/${SERVICENAME}.plist /Library/LaunchAgents/${SERVICENAME}.plist \
    /Library/LaunchDaemons/meshagent.plist /Library/LaunchAgents/meshagent.plist 2>/dev/null || true)
if [[ -n "$PLISTS" ]]; then
    echo -e "${RED}  X plists residuales:${NC}"
    echo "$PLISTS"
    ALL_CLEAN=false
else
    echo -e "${GREEN}  OK plists: ninguno${NC}"
fi

LCTL_USER=$(launchctl list | grep -iE "mesh|ZH_Cons" || true)
LCTL_SYS=$(sudo launchctl list | grep -iE "mesh|ZH_Cons" || true)
if [[ -n "$LCTL_USER" || -n "$LCTL_SYS" ]]; then
    echo -e "${RED}  X launchctl residual:${NC}"
    [[ -n "$LCTL_USER" ]] && echo "    user: $LCTL_USER"
    [[ -n "$LCTL_SYS"  ]] && echo "    system: $LCTL_SYS"
    ALL_CLEAN=false
else
    echo -e "${GREEN}  OK launchctl: limpio${NC}"
fi

echo ""
if $ALL_CLEAN; then
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  UNINSTALL COMPLETO${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo ""
    echo -e "${WHITE}Para reinstalar limpio:${NC}"
    echo -e "  bash <(curl -fsSL https://zh.com.pa/mcimac)"
    echo ""
    echo -e "${WHITE}Para borrar el nodo offline en MeshCentral:${NC}"
    echo -e "  click derecho sobre el nodo en https://mc.zhconsultores.com -> Delete Device"
    exit 0
else
    echo -e "${RED}========================================${NC}"
    echo -e "${RED}  UNINSTALL INCOMPLETO${NC}"
    echo -e "${RED}========================================${NC}"
    echo -e "${YELLOW}Reintentar el script. Si persiste, reiniciar la Mac y correr de nuevo.${NC}"
    exit 1
fi
