#!/bin/bash
# Script pour lister les paquets installés manuellement sur Raspberry Pi
# Destiné à mettre à jour install.sh pour Skull Pi

set -euo pipefail

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

# Fichiers de sortie
OUTPUT_FILE="manual_packages_$(date +%Y%m%d_%H%M%S).txt"
INSTALL_TEMPLATE="install_packages_template.sh"

echo -e "${BLUE}🔍 Analyse des paquets manuels du Raspberry Pi${NC}"
echo -e "${BLUE}===============================================${NC}"
echo ""

# Vérification si on est sur un Raspberry Pi
if ! grep -q "BCM" /proc/cpuinfo 2>/dev/null; then
    echo -e "${YELLOW}⚠️  Ce système ne semble pas être un Raspberry Pi${NC}"
    echo -e "${YELLOW}   Continuez-vous quand même ? (y/N)${NC}"
    read -r -n 1 response
    echo ""
    if [[ ! $response =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

echo -e "${GREEN}📊 Collecte des informations système...${NC}"

{
    echo "# Analyse des paquets installés manuellement"
    echo "# ==========================================="
    echo "# Date: $(date)"
    echo "# Système: $(uname -a)"
    echo "# OS: $(cat /etc/os-release | grep PRETTY_NAME | cut -d'=' -f2 | tr -d '\"')"
    echo ""
    
    # Informations sur l'installation
    if [ -f /var/log/installer/media-info ]; then
        echo "# Installation originale:"
        cat /var/log/installer/media-info 2>/dev/null | head -3 || echo "# Info non disponible"
    fi
    echo ""

} > "$OUTPUT_FILE"

echo -e "${GREEN}📦 Récupération des paquets installés manuellement...${NC}"

# Méthode 1: Paquets marqués comme installés manuellement
echo "## METHODE 1: apt-mark showmanual" >> "$OUTPUT_FILE"
echo "## ================================" >> "$OUTPUT_FILE"
apt-mark showmanual | sort >> "$OUTPUT_FILE"
echo "" >> "$OUTPUT_FILE"

# Méthode 2: Paquets installés manuellement (excluant ceux de l'installation de base)
echo "## METHODE 2: Paquets ajoutés post-installation" >> "$OUTPUT_FILE"
echo "## =============================================" >> "$OUTPUT_FILE"

if [ -f /var/log/installer/initial-status.gz ]; then
    echo "# Paquets installés après l'installation initiale du système" >> "$OUTPUT_FILE"
    comm -23 \
        <(apt-mark showmanual | sort) \
        <(gzip -dc /var/log/installer/initial-status.gz 2>/dev/null | sed -n 's/^Package: //p' | sort) \
        >> "$OUTPUT_FILE"
else
    echo "# Fichier initial-status.gz non disponible" >> "$OUTPUT_FILE"
    echo "# Utilisation de la liste complète des paquets manuels" >> "$OUTPUT_FILE"
    apt-mark showmanual | sort >> "$OUTPUT_FILE"
fi
echo "" >> "$OUTPUT_FILE"

# Méthode 3: Analyse des logs récents
echo "## METHODE 3: Paquets installés récemment (30 derniers jours)" >> "$OUTPUT_FILE"
echo "## =========================================================" >> "$OUTPUT_FILE"

if [ -f /var/log/dpkg.log ]; then
    echo "# Installations des 30 derniers jours" >> "$OUTPUT_FILE"
    grep " install " /var/log/dpkg.log 2>/dev/null | \
        grep "$(date -d '30 days ago' '+%Y-%m-%d')" | \
        awk '{print $4}' | cut -d: -f1 | sort -u >> "$OUTPUT_FILE" || \
        echo "# Aucune installation récente trouvée" >> "$OUTPUT_FILE"
else
    echo "# Log dpkg non disponible" >> "$OUTPUT_FILE"
fi
echo "" >> "$OUTPUT_FILE"

# Analyse par catégorie
echo -e "${GREEN}🏷️  Analyse par catégories...${NC}"

echo "## ANALYSE PAR CATEGORIES" >> "$OUTPUT_FILE"
echo "## =======================" >> "$OUTPUT_FILE"

# Fonction pour filtrer les paquets par catégorie
filter_category() {
    local category="$1"
    local pattern="$2"
    local description="$3"
    
    echo "" >> "$OUTPUT_FILE"
    echo "### $category" >> "$OUTPUT_FILE"
    echo "# $description" >> "$OUTPUT_FILE"
    
    apt-mark showmanual | grep -E "$pattern" | sort >> "$OUTPUT_FILE" || \
        echo "# Aucun paquet trouvé pour cette catégorie" >> "$OUTPUT_FILE"
}

# Catégories d'analyse
filter_category "PYTHON" "python" "Environnement Python et outils"
filter_category "DEVELOPMENT" "(build|essential|dev|git|curl|wget|cmake|make)" "Outils de développement"
filter_category "AUDIO" "(alsa|pulse|audio|sound|espeak|festival|flite)" "Système audio et TTS"
filter_category "VIDEO" "(video|camera|opencv|v4l|ffmpeg|gst)" "Vidéo, caméra et multimédia"
filter_category "MQTT" "(mosquitto|mqtt)" "Protocole MQTT"
filter_category "NETWORKING" "(network|wifi|bluetooth|ssh)" "Réseau et communication"
filter_category "LIBRARIES" "(lib.*-dev|.*-dev)" "Bibliothèques de développement"
filter_category "HARDWARE" "(gpio|i2c|spi|rpi|wiringpi|pigpio)" "Accès matériel Raspberry Pi"
filter_category "SYSTEM_TOOLS" "(systemd|cron|htop|nano|vim|tree|unzip)" "Outils système"

echo "" >> "$OUTPUT_FILE"

# Génération du template pour install.sh
echo -e "${GREEN}⚙️  Génération du template install.sh...${NC}"

{
    echo "#!/bin/bash"
    echo "# Template généré automatiquement pour les dépendances"
    echo "# Date: $(date)"
    echo "# Basé sur l'analyse de: $(hostname)"
    echo ""
    echo "# PAQUETS ESSENTIELS DETECTES"
    echo "# ============================"
    echo ""
    echo "# Installation des dépendances système"
    echo 'echo "📥 Installation des dépendances système..."'
    echo "apt-get install -y \\"
    
    # Paquets suggérés basés sur l'analyse
    SUGGESTED_PACKAGES=(
        "python3-venv"
        "python3-pip"
        "python3-dev"
        "build-essential"
        "git"
        "curl"
        "wget"
        "nano"
        "mosquitto"
        "mosquitto-clients"
    )
    
    # Vérifier quels paquets sont effectivement installés
    echo "    # Core system packages"
    for pkg in "${SUGGESTED_PACKAGES[@]}"; do
        if apt-mark showmanual | grep -q "^$pkg$"; then
            echo "    $pkg \\"
        fi
    done
    
    # Ajouter les paquets spécifiques trouvés
    echo "    # Audio packages"
    apt-mark showmanual | grep -E "(alsa|audio|espeak|portaudio)" | while read -r pkg; do
        echo "    $pkg \\"
    done 2>/dev/null || true
    
    echo "    # Video/Camera packages"
    apt-mark showmanual | grep -E "(opencv|ffmpeg|v4l)" | while read -r pkg; do
        echo "    $pkg \\"
    done 2>/dev/null || true
    
    echo "    # Development libraries"
    apt-mark showmanual | grep -E "(libatlas|lib.*-dev)" | head -10 | while read -r pkg; do
        echo "    $pkg \\"
    done 2>/dev/null || true
    
    echo ""
    echo "# Nettoyer la dernière ligne (enlever le backslash final manuellement)"
    echo ""
    echo "# VERIFICATION"
    echo "# ============"
    echo 'echo "✅ Vérification des installations..."'
    echo ""
    echo "# Ajoutez ici vos vérifications spécifiques"
    echo ""
    echo "# LISTE COMPLETE DES PAQUETS MANUELS DETECTES:"
    echo "# $(apt-mark showmanual | wc -l) paquets au total"
    echo "#"
    apt-mark showmanual | sed 's/^/# /'
    
} > "$INSTALL_TEMPLATE"

chmod +x "$INSTALL_TEMPLATE"

echo "" 
echo -e "${GREEN}✅ Analyse terminée !${NC}"
echo ""
echo -e "${YELLOW}📋 Fichiers générés:${NC}"
echo -e "  📄 ${BLUE}$OUTPUT_FILE${NC} - Analyse complète des paquets"
echo -e "  📄 ${BLUE}$INSTALL_TEMPLATE${NC} - Template pour install.sh"
echo ""

echo -e "${YELLOW}📊 Résumé:${NC}"
echo -e "  🔢 Paquets manuels total: ${GREEN}$(apt-mark showmanual | wc -l)${NC}"

if [ -f /var/log/installer/initial-status.gz ]; then
    POST_INSTALL_COUNT=$(comm -23 <(apt-mark showmanual | sort) <(gzip -dc /var/log/installer/initial-status.gz 2>/dev/null | sed -n 's/^Package: //p' | sort) | wc -l)
    echo -e "  📦 Paquets ajoutés post-install: ${GREEN}$POST_INSTALL_COUNT${NC}"
fi

echo ""
echo -e "${YELLOW}🔧 Prochaines étapes:${NC}"
echo -e "  1. Examinez ${BLUE}$OUTPUT_FILE${NC} pour identifier les paquets nécessaires"
echo -e "  2. Utilisez ${BLUE}$INSTALL_TEMPLATE${NC} comme base pour modifier install.sh"
echo -e "  3. Testez sur un Raspberry Pi neuf"
echo -e "  4. Ajustez selon les besoins spécifiques de Skull Pi"
echo ""

echo -e "${YELLOW}💡 Commandes utiles:${NC}"
echo -e "  📖 Voir l'analyse: ${BLUE}less $OUTPUT_FILE${NC}"
echo -e "  ✏️  Éditer template: ${BLUE}nano $INSTALL_TEMPLATE${NC}"
echo -e "  🔍 Rechercher un paquet: ${BLUE}grep 'nom_paquet' $OUTPUT_FILE${NC}"