#!/bin/bash
# nas-docker-pull — Pull les images Docker et détecte les mises à jour disponibles
# Usage : nas-docker-pull
# Output : JSON (mode non-interactif) ou texte coloré (mode terminal)
# Idempotent : tant que nas-docker-up n'a pas recréé les conteneurs,
#              le conteneur tourne sur l'ancien image ID → l'écart est toujours détecté

set -euo pipefail

if [ -t 1 ]; then INTERACTIVE=true; else INTERACTIVE=false; fi

# Couleurs (mode terminal uniquement)
if $INTERACTIVE; then
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    CYAN='\033[0;36m'
    BOLD='\033[1m'
    RESET='\033[0m'
else
    RED='' GREEN='' YELLOW='' CYAN='' BOLD='' RESET=''
fi

containers_json=""
count=0

if $INTERACTIVE; then
    echo -e "${BOLD}--- Vérification des images Docker ---${RESET}"
fi

while IFS=: read -r container_id container_name; do
    # Récupérer le compose_dir via le label
    compose_dir=$(docker inspect --format='{{index .Config.Labels "com.docker.compose.project.working_dir"}}' "$container_id" 2>/dev/null | xargs)

    # Ignorer les conteneurs hors compose
    if [ -z "$compose_dir" ] || [ ! -d "$compose_dir" ]; then
        continue
    fi

    image_name=$(docker inspect --format='{{.Config.Image}}' "$container_id")
    old_image_id=$(docker inspect --format='{{.Image}}' "$container_id")
    old_ver=$(docker inspect --format='{{index .Config.Labels "org.opencontainers.image.version"}}' "$container_id" 2>/dev/null || echo "")
    [ -z "$old_ver" ] && old_ver="inconnue"

    if $INTERACTIVE; then
        echo -ne "  Vérification de ${CYAN}${container_name}${RESET}... "
    fi

    if ! docker pull "$image_name" > /dev/null 2>&1; then
        if $INTERACTIVE; then echo -e "${YELLOW}⚠ Erreur de pull (ignoré)${RESET}"; fi
        continue
    fi

    new_image_id=$(docker inspect --format='{{.Id}}' "$image_name" 2>/dev/null)

    if [ "$old_image_id" != "$new_image_id" ]; then
        new_ver=$(docker inspect --format='{{index .Config.Labels "org.opencontainers.image.version"}}' "$image_name" 2>/dev/null || echo "")
        [ -z "$new_ver" ] && new_ver="disponible"

        if $INTERACTIVE; then
            echo -e "${YELLOW}MAJ DISPONIBLE${RESET} : ${YELLOW}${old_ver}${RESET} → ${GREEN}${new_ver}${RESET}"
        fi

        entry="{\"name\":\"${container_name}\",\"image\":\"${image_name}\",\"compose_dir\":\"${compose_dir}\",\"current\":\"${old_ver}\",\"available\":\"${new_ver}\"}"
        if [ $count -eq 0 ]; then
            containers_json="${entry}"
        else
            containers_json="${containers_json},${entry}"
        fi
        count=$((count + 1))
    else
        if $INTERACTIVE; then echo -e "${GREEN}✅ À jour${RESET}"; fi
    fi

done < <(docker ps --format "{{.ID}}:{{.Names}}")

# Toujours écrire le JSON dans /tmp pour nas-update
printf '{"count":%d,"containers":[%s]}\n' "$count" "$containers_json" > /tmp/nas-docker-pull.json

if $INTERACTIVE; then
    echo ""
    echo -e "${BOLD}--- Bilan ---${RESET}"
    if [ $count -eq 0 ]; then
        echo -e "${GREEN}✅ Tous les conteneurs sont à jour.${RESET}"
    else
        echo -e "${YELLOW}🐳 ${count} conteneur(s) à mettre à jour.${RESET}"
    fi
else
    cat /tmp/nas-docker-pull.json
fi
