#!/bin/bash
# ============================================================
# MonitorPing — Limpeza Completa
# Remove instalação anterior para permitir reinstalação limpa
# Uso: sudo bash cleanup.sh
# ============================================================
set -euo pipefail

MP_USER="monitorping"
INSTALL_DIR="/opt/monitorping"

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BOLD='\033[1m'; NC='\033[0m'

log()  { echo -e "  ${GREEN}✓${NC} $1"; }
info() { echo -e "  ${YELLOW}→${NC} $1"; }

[[ $EUID -ne 0 ]] && { echo -e "${RED}Execute com sudo: sudo bash cleanup.sh${NC}"; exit 1; }

echo ""
echo -e "${BOLD}${RED}  ╔══════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${RED}  ║      MonitorPing — Limpeza Completa          ║${NC}"
echo -e "${BOLD}${RED}  ╚══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${YELLOW}⚠  Isso irá remover TODOS os dados do MonitorPing,${NC}"
echo -e "  ${YELLOW}   incluindo banco de dados, containers e arquivos.${NC}"
echo ""
read -r -p "  Confirma? Digite SIM para continuar: " CONFIRM
[[ "$CONFIRM" != "SIM" ]] && { echo "  Cancelado."; exit 0; }
echo ""

MP_UID=$(id -u "$MP_USER" 2>/dev/null || echo 0)

# ── 1. Para e remove containers e volumes ───────────────────
info "Parando containers..."
if [[ "$MP_UID" -gt 0 ]] && [[ -f "$INSTALL_DIR/docker-compose.prod.yml" ]]; then
    sudo -u "$MP_USER" \
        XDG_RUNTIME_DIR="/run/user/$MP_UID" \
        DOCKER_HOST="unix:///run/user/$MP_UID/docker.sock" \
        docker compose -f "$INSTALL_DIR/docker-compose.prod.yml" \
        --env-file "$INSTALL_DIR/.env" \
        down -v 2>/dev/null || true
fi
log "Containers e volumes removidos"

# ── 2. Remove imagem Docker ──────────────────────────────────
info "Removendo imagem Docker..."
if [[ "$MP_UID" -gt 0 ]]; then
    sudo -u "$MP_USER" \
        XDG_RUNTIME_DIR="/run/user/$MP_UID" \
        DOCKER_HOST="unix:///run/user/$MP_UID/docker.sock" \
        docker rmi monitorping-app:latest 2>/dev/null || true
fi
log "Imagem removida"

# ── 3. Para o daemon Docker rootless ────────────────────────
info "Parando daemon Docker rootless..."
if [[ "$MP_UID" -gt 0 ]]; then
    sudo -u "$MP_USER" \
        XDG_RUNTIME_DIR="/run/user/$MP_UID" \
        systemctl --user stop docker 2>/dev/null || true
fi
log "Daemon parado"

# ── 4. Remove serviços systemd ───────────────────────────────
info "Removendo serviços systemd..."
for svc in monitorping monitorping-update-watcher monitorping-update.timer monitorping-update; do
    systemctl stop "$svc" 2>/dev/null || true
    systemctl disable "$svc" 2>/dev/null || true
done
rm -f /etc/systemd/system/monitorping.service
rm -f /etc/systemd/system/monitorping-dockerd.service
rm -f /etc/systemd/system/monitorping-update-watcher.service
rm -f /etc/systemd/system/monitorping-update.service
rm -f /etc/systemd/system/monitorping-update.timer
systemctl daemon-reload
log "Serviços removidos"

# ── 5. Remove storage do Docker e config ────────────────────
info "Limpando storage Docker..."
rm -rf "/home/$MP_USER/.local/share/docker"
rm -rf "/home/$MP_USER/.config/docker"
log "Storage Docker removido"

# ── 6. Remove arquivos de instalação ────────────────────────
info "Removendo arquivos do MonitorPing..."
rm -rf "$INSTALL_DIR"
log "Arquivos removidos"

# ── 7. Remove usuário monitorping ───────────────────────────
info "Removendo usuário $MP_USER..."
userdel -r "$MP_USER" 2>/dev/null || true
sed -i "/^$MP_USER:/d" /etc/subuid 2>/dev/null || true
sed -i "/^$MP_USER:/d" /etc/subgid 2>/dev/null || true
log "Usuário removido"

# ── 8. Remove logs e backups ─────────────────────────────────
info "Removendo logs e backups..."
rm -f /var/log/monitorping-install.log
rm -rf /var/backups/monitorping
log "Logs e backups removidos"

# ── 9. Firewall ──────────────────────────────────────────────
if command -v ufw &>/dev/null; then
    ufw delete allow 80/tcp comment "MonitorPing" 2>/dev/null || true
    ufw delete allow 443/tcp comment "MonitorPing" 2>/dev/null || true
fi

echo ""
echo -e "${GREEN}${BOLD}  ✓ Limpeza concluída! Sistema pronto para nova instalação.${NC}"
echo ""
echo -e "  Para instalar: ${BOLD}sudo bash install.sh${NC}"
echo ""
