#!/bin/bash
# Script de diagnostic utilisateur pour Skull Pi
# Vérifie la configuration utilisateur actuelle

set -euo pipefail

# Couleurs
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}🔍 Diagnostic utilisateur Skull Pi${NC}"
echo -e "${BLUE}=================================${NC}"
echo ""

# Détection de l'utilisateur configuré
SKULL_USER=""
if [ -f "/opt/Skull/config/.env" ]; then
    SKULL_USER=$(stat -c %U /opt/Skull/config/.env)
elif [ -d "/opt/Skull" ]; then
    SKULL_USER=$(stat -c %U /opt/Skull)
else
    echo -e "${RED}❌ Répertoire /opt/Skull non trouvé${NC}"
    echo "   Le système Skull Pi n'est pas installé"
    exit 1
fi

echo -e "${YELLOW}👤 Utilisateur configuré: ${GREEN}$SKULL_USER${NC}"

# Vérifier si l'utilisateur existe
if ! id "$SKULL_USER" &>/dev/null; then
    echo -e "${RED}❌ L'utilisateur '$SKULL_USER' n'existe plus sur ce système !${NC}"
    echo ""
    echo -e "${YELLOW}🔧 Solutions possibles:${NC}"
    echo "1. Recréer l'utilisateur: sudo useradd -m $SKULL_USER"
    echo "2. Réinstaller avec l'utilisateur actuel: sudo bash install.sh"
    echo "3. Changer le propriétaire: sudo chown -R \$USER:\$USER /opt/Skull"
    exit 1
else
    echo -e "${GREEN}✅ Utilisateur exists et est valide${NC}"
fi

# Informations sur l'utilisateur
USER_UID=$(id -u "$SKULL_USER")
USER_GID=$(id -g "$SKULL_USER")
USER_HOME=$(getent passwd "$SKULL_USER" | cut -d: -f6)

echo ""
echo -e "${YELLOW}📊 Informations utilisateur:${NC}"
echo "   UID: $USER_UID"
echo "   GID: $USER_GID"
echo "   Home: $USER_HOME"
echo "   Groupes: $(groups "$SKULL_USER" 2>/dev/null | cut -d: -f2 || echo "Impossible de lister")"

# Vérification des services systemd
echo ""
echo -e "${YELLOW}⚙️ Configuration services systemd:${NC}"

SERVICES=("skull-orchestrator" "skull-motion" "skull-vision" "skull-voice" "skull-audioin" "skull-asr" "skull-ai")

for service in "${SERVICES[@]}"; do
    if [ -f "/etc/systemd/system/$service.service" ]; then
        CONFIGURED_USER=$(grep "^User=" "/etc/systemd/system/$service.service" | cut -d= -f2 || echo "Non défini")
        if [ "$CONFIGURED_USER" = "$SKULL_USER" ]; then
            echo -e "   ✅ $service: ${GREEN}$CONFIGURED_USER${NC}"
        else
            echo -e "   ❌ $service: ${RED}$CONFIGURED_USER (attendu: $SKULL_USER)${NC}"
        fi
    else
        echo -e "   ❌ $service: ${RED}Service manquant${NC}"
    fi
done

# Vérification sudoers
echo ""
echo -e "${YELLOW}🔐 Configuration sudoers:${NC}"
if [ -f "/etc/sudoers.d/skull" ]; then
    SUDOERS_USER=$(grep "^[a-zA-Z]" /etc/sudoers.d/skull | head -1 | cut -d' ' -f1)
    if [ "$SUDOERS_USER" = "$SKULL_USER" ]; then
        echo -e "   ✅ Sudoers: ${GREEN}$SUDOERS_USER${NC}"
    else
        echo -e "   ❌ Sudoers: ${RED}$SUDOERS_USER (attendu: $SKULL_USER)${NC}"
    fi
else
    echo -e "   ❌ Fichier sudoers manquant: ${RED}/etc/sudoers.d/skull${NC}"
fi

# Vérification des permissions fichiers
echo ""
echo -e "${YELLOW}📁 Permissions fichiers:${NC}"

DIRECTORIES=("/opt/Skull" "/opt/Skull/config" "/opt/Skull/logs" "/opt/Skull/venv")

for dir in "${DIRECTORIES[@]}"; do
    if [ -d "$dir" ]; then
        OWNER=$(stat -c %U "$dir")
        if [ "$OWNER" = "$SKULL_USER" ]; then
            echo -e "   ✅ $dir: ${GREEN}$OWNER${NC}"
        else
            echo -e "   ❌ $dir: ${RED}$OWNER (attendu: $SKULL_USER)${NC}"
        fi
    else
        echo -e "   ❌ $dir: ${RED}Répertoire manquant${NC}"
    fi
done

# Vérification PulseAudio
echo ""
echo -e "${YELLOW}🔊 Configuration PulseAudio:${NC}"
PULSE_DIR="/run/user/$USER_UID/pulse"
if [ -d "$PULSE_DIR" ]; then
    echo -e "   ✅ Runtime PulseAudio: ${GREEN}$PULSE_DIR${NC}"
else
    echo -e "   ⚠️  Runtime PulseAudio: ${YELLOW}$PULSE_DIR (sera créé au besoin)${NC}"
fi

# Vérification des groupes nécessaires
echo ""
echo -e "${YELLOW}👥 Groupes système:${NC}"
REQUIRED_GROUPS=("audio" "video" "gpio" "i2c" "spi")

for group in "${REQUIRED_GROUPS[@]}"; do
    if getent group "$group" >/dev/null 2>&1; then
        if groups "$SKULL_USER" 2>/dev/null | grep -q "\b$group\b"; then
            echo -e "   ✅ $group: ${GREEN}Membre${NC}"
        else
            echo -e "   ⚠️  $group: ${YELLOW}Non membre${NC}"
        fi
    else
        echo -e "   ❌ $group: ${RED}Groupe inexistant${NC}"
    fi
done

# Résumé et recommandations
echo ""
echo -e "${BLUE}📝 DIAGNOSTIC:${NC}"

# Compter les problèmes
ISSUES=0

# Utilisateur existe ?
if ! id "$SKULL_USER" &>/dev/null; then
    ((ISSUES++))
fi

# Services configurés ?
for service in "${SERVICES[@]}"; do
    if [ -f "/etc/systemd/system/$service.service" ]; then
        CONFIGURED_USER=$(grep "^User=" "/etc/systemd/system/$service.service" | cut -d= -f2 || echo "Non défini")
        if [ "$CONFIGURED_USER" != "$SKULL_USER" ]; then
            ((ISSUES++))
            break
        fi
    fi
done

# Permissions OK ?
for dir in "${DIRECTORIES[@]}"; do
    if [ -d "$dir" ]; then
        OWNER=$(stat -c %U "$dir")
        if [ "$OWNER" != "$SKULL_USER" ]; then
            ((ISSUES++))
            break
        fi
    fi
done

if [ $ISSUES -eq 0 ]; then
    echo -e "   🎉 ${GREEN}Configuration utilisateur CORRECTE${NC}"
    echo -e "   ✅ Skull Pi configuré pour l'utilisateur: $SKULL_USER"
else
    echo -e "   ⚠️  ${YELLOW}$ISSUES problème(s) de configuration utilisateur${NC}"
    echo ""
    echo -e "${YELLOW}🔧 Recommandations:${NC}"
    echo "1. Réinstaller avec l'utilisateur courant:"
    echo "   sudo bash install.sh"
    echo ""
    echo "2. Ou corriger manuellement les permissions:"
    echo "   sudo chown -R $SKULL_USER:$SKULL_USER /opt/Skull"
    echo "   sudo systemctl daemon-reload"
    echo "   sudo systemctl restart skull.target"
fi