#!/bin/bash
# =============================================================================
#  setup-netdata.sh — Checklist système + Docker + Netdata
# =============================================================================

set -e

# ── Couleurs ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
RESET='\033[0m'

OK="${GREEN}[OK]${RESET}"
FAIL="${RED}[FAIL]${RESET}"
INFO="${CYAN}[INFO]${RESET}"
WARN="${YELLOW}[WARN]${RESET}"

# ── Banner ────────────────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}${CYAN}=============================================${RESET}"
echo -e "${BOLD}${CYAN}     CHECKLIST SYSTÈME — SETUP NETDATA       ${RESET}"
echo -e "${BOLD}${CYAN}=============================================${RESET}"
echo ""

# =============================================================================
# 1. CHECKLIST SYSTÈME
# =============================================================================
echo -e "${BOLD}>>> 1. INFORMATIONS SYSTÈME${RESET}"
echo "---------------------------------------------"

# Hostname
HOSTNAME_VAL=$(hostname)
echo -e "  Hostname       : ${BOLD}${HOSTNAME_VAL}${RESET}"

# Type de machine (bare-metal / VM / container)
if [ -f /sys/class/dmi/id/product_name ]; then
    PRODUCT=$(cat /sys/class/dmi/id/product_name 2>/dev/null || echo "inconnu")
else
    PRODUCT="inconnu"
fi

if systemd-detect-virt --quiet 2>/dev/null; then
    MACHINE_TYPE="Virtuelle ($(systemd-detect-virt 2>/dev/null || echo 'VM'))"
elif grep -q "container" /proc/1/environ 2>/dev/null; then
    MACHINE_TYPE="Conteneur"
else
    MACHINE_TYPE="Physique / Bare-metal (${PRODUCT})"
fi
echo -e "  Type machine   : ${BOLD}${MACHINE_TYPE}${RESET}"

# Adresse(s) IP
IP_LIST=$(hostname -I 2>/dev/null | tr ' ' '\n' | grep -v '^$' | head -5)
echo -e "  Adresse(s) IP  :"
while IFS= read -r ip; do
    echo -e "    - ${BOLD}${ip}${RESET}"
done <<< "$IP_LIST"

# OS / Distro
if [ -r /etc/os-release ]; then
    OS_NAME=$(. /etc/os-release && echo "$PRETTY_NAME")
else
    OS_NAME="Inconnu"
fi
echo -e "  OS             : ${BOLD}${OS_NAME}${RESET}"

# Noyau
echo -e "  Kernel         : ${BOLD}$(uname -r)${RESET}"

# Arch
echo -e "  Architecture   : ${BOLD}$(uname -m)${RESET}"

echo ""

# =============================================================================
# 2. VARIABLE D'ENVIRONNEMENT & FICHIER .env
# =============================================================================
echo -e "${BOLD}>>> 2. VARIABLE D'ENVIRONNEMENT${RESET}"
echo "---------------------------------------------"

export HOSTNAME_ENV="${HOSTNAME_VAL}"
echo -e "  ${OK} Variable HOSTNAME_ENV exportée : ${BOLD}${HOSTNAME_ENV}${RESET}"

# Création du fichier .env temporaire (sera déplacé dans /opt/netdata plus tard)
ENV_TMP="/tmp/netdata.env"
cat > "${ENV_TMP}" <<EOF
# Généré par setup-netdata.sh le $(date '+%Y-%m-%d %H:%M:%S')
HOSTNAME=${HOSTNAME_VAL}
EOF

echo -e "  ${OK} Fichier .env créé dans ${ENV_TMP}"
echo ""

# =============================================================================
# 3. VÉRIFICATION DOCKER
# =============================================================================
echo -e "${BOLD}>>> 3. VÉRIFICATION DOCKER${RESET}"
echo "---------------------------------------------"

if command -v docker > /dev/null 2>&1; then
    DOCKER_VER=$(docker --version 2>/dev/null)
    echo -e "  ${OK} Docker installé — ${BOLD}${DOCKER_VER}${RESET}"

    # Vérifier que le démon tourne
    if docker info > /dev/null 2>&1; then
        echo -e "  ${OK} Docker daemon actif"
    else
        echo -e "  ${WARN} Docker installé mais le daemon ne répond pas."
        echo -e "       Tentative de démarrage..."
        sudo systemctl start docker || true
    fi
    DOCKER_OK=1
else
    echo -e "  ${FAIL} Docker ${RED}non détecté${RESET} — lancement de l'installation..."
    echo ""

    # ── Installation de Docker via le script officiel ─────────────────────────
    INSTALL_SCRIPT="/tmp/install-docker.sh"

    # On cherche d'abord si le script fourni est dans le même dossier
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    if [ -f "${SCRIPT_DIR}/install-docker.sh" ]; then
        echo -e "  ${INFO} Utilisation du script local : ${SCRIPT_DIR}/install-docker.sh"
        cp "${SCRIPT_DIR}/install-docker.sh" "${INSTALL_SCRIPT}"
    else
        echo -e "  ${INFO} Téléchargement du script Docker officiel..."
        curl -fsSL https://get.docker.com -o "${INSTALL_SCRIPT}"
    fi

    chmod +x "${INSTALL_SCRIPT}"
    echo -e "  ${INFO} Exécution du script d'installation Docker..."
    sudo sh "${INSTALL_SCRIPT}"

    # Activer et démarrer Docker
    sudo systemctl enable docker
    sudo systemctl start docker

    if command -v docker > /dev/null 2>&1; then
        echo -e "  ${OK} Docker installé avec succès — $(docker --version)"
        DOCKER_OK=1
    else
        echo -e "  ${FAIL} L'installation de Docker a échoué. Abandon."
        exit 1
    fi
fi

echo ""

# =============================================================================
# 4. VÉRIFICATION DOCKER COMPOSE
# =============================================================================
echo -e "${BOLD}>>> 4. VÉRIFICATION DOCKER COMPOSE${RESET}"
echo "---------------------------------------------"

if docker compose version > /dev/null 2>&1; then
    echo -e "  ${OK} docker compose (plugin) disponible — $(docker compose version)"
    COMPOSE_CMD="docker compose"
elif command -v docker-compose > /dev/null 2>&1; then
    echo -e "  ${OK} docker-compose (standalone) disponible — $(docker-compose --version)"
    COMPOSE_CMD="docker-compose"
else
    echo -e "  ${FAIL} Docker Compose introuvable. Abandon."
    exit 1
fi

echo ""

# =============================================================================
# 5. CRÉATION DU DOSSIER /opt/netdata ET DÉPÔT DES FICHIERS
# =============================================================================
echo -e "${BOLD}>>> 5. CRÉATION DE /opt/netdata${RESET}"
echo "---------------------------------------------"

NETDATA_DIR="/opt/netdata"

sudo mkdir -p "${NETDATA_DIR}"
echo -e "  ${OK} Dossier créé : ${NETDATA_DIR}"

# Sous-dossiers pour les volumes
for d in config lib cache; do
    sudo mkdir -p "${NETDATA_DIR}/${d}"
done
echo -e "  ${OK} Sous-dossiers config / lib / cache créés"

# Déplacer le .env dans /opt/netdata
sudo cp "${ENV_TMP}" "${NETDATA_DIR}/.env"
echo -e "  ${OK} Fichier .env copié dans ${NETDATA_DIR}/.env"

# =============================================================================
# 6. CRÉATION DU docker-compose.yml
# =============================================================================
echo -e ""
echo -e "${BOLD}>>> 6. GÉNÉRATION DU docker-compose.yml${RESET}"
echo "---------------------------------------------"

sudo tee "${NETDATA_DIR}/docker-compose.yml" > /dev/null <<'COMPOSE'
services:
  netdata:
    image: netdata/netdata:latest
    container_name: netdata
    hostname: ${HOSTNAME}
    env_file:
      - .env
    network_mode: host
    cap_add:
      - SYS_PTRACE
    security_opt:
      - apparmor=unconfined
    volumes:
      - /opt/netdata/config:/etc/netdata
      - /opt/netdata/lib:/var/lib/netdata
      - /opt/netdata/cache:/var/cache/netdata
      - /:/host/root:ro,rslave
      - /proc:/host/proc:ro
      - /sys:/host/sys:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - /etc/passwd:/host/etc/passwd:ro
      - /etc/group:/host/etc/group:ro
    restart: unless-stopped
COMPOSE

echo -e "  ${OK} docker-compose.yml créé dans ${NETDATA_DIR}"

# =============================================================================
# 7. LANCEMENT DE NETDATA
# =============================================================================
echo ""
echo -e "${BOLD}>>> 7. DÉMARRAGE DE NETDATA${RESET}"
echo "---------------------------------------------"

cd "${NETDATA_DIR}"
sudo ${COMPOSE_CMD} up -d


echo ""
if sudo ${COMPOSE_CMD} ps | grep -q "netdata"; then
    echo -e "  ${OK} ${BOLD}Netdata est démarré !${RESET}"
    echo -e "  ${INFO} Dashboard disponible sur : ${CYAN}http://${IP_LIST%%$'\n'*}:19999${RESET}"
    CONTAINER_UP=1
else
    echo -e "  ${WARN} Le conteneur ne semble pas démarré. Vérifiez avec :"
    echo -e "       sudo docker compose -f ${NETDATA_DIR}/docker-compose.yml logs"
    CONTAINER_UP=0
fi

# =============================================================================
# 8. CONFIGURATION DU STREAMING (stream.conf)
# =============================================================================
echo ""
echo -e "${BOLD}>>> 8. CONFIGURATION STREAM.CONF${RESET}"
echo "---------------------------------------------"

if [ "$CONTAINER_UP" = "1" ]; then

    STREAM_CONF="${NETDATA_DIR}/config/stream.conf"

    sudo tee "${STREAM_CONF}" > /dev/null << 'STREAMCONF'
# netdata configuration for aggregating data from remote hosts
#
# API keys authorize a pair of sending-receiving netdata servers.
# Once their communication is authorized, they can exchange metrics for any
# number of hosts.
#
# You can generate API keys, with the linux command: uuidgen


# -----------------------------------------------------------------------------
# 1. ON CHILD NETDATA - THE ONE THAT WILL BE SENDING METRICS

[stream]
    # Enable this on child nodes, to have them send metrics.
    enabled = yes

    # Where is the receiving netdata?
    destination = 172.0.16.236:19999

    # The API_KEY to use (as the sender)
    api key = d81b68b9-f532-4e3c-93f3-12e99a51c8cc

    #ssl skip certificate verification = yes
    #CApath =
    #CAfile =
    #enable compression = yes
    #timeout = 5m
    #default port = 19999
    #send charts matching = *
    #buffer size = 10MiB
    #reconnect delay = 15s
    #initial clock resync iterations = 60

# -----------------------------------------------------------------------------
# 2. ON PARENT NETDATA - THE ONE THAT WILL BE RECEIVING METRICS

[API_KEY]
    type = api
    enabled = no
    #allow from = *
    #retention = 3600
    #db = dbengine
    #health enabled = auto
    #postpone alerts on connect = 1m
    #health log retention = 5d
    #proxy enabled = yes | no
    #proxy destination = IP:PORT IP:PORT ...
    #proxy api key = API_KEY
    #proxy send charts matching = *
    #enable compression = yes
    #compression algorithms order = zstd lz4 brotli gzip
    #enable replication = yes
    #replication period = 1d
    #replication step = 10m
    #is ephemeral node = no

# -----------------------------------------------------------------------------
# 3. PER SENDING HOST SETTINGS, ON PARENT NETDATA

[MACHINE_GUID]
    type = machine
    enabled = no
    #allow from = *
    #retention = 3600
    #db = dbengine
    #health enabled = auto
    #postpone alerts on connect = 1m
    #health log retention = 5d
    #proxy enabled = yes | no
    #proxy destination = IP:PORT IP:PORT ...
    #proxy api key = API_KEY
    #proxy send charts matching = *
    #enable compression = yes
    #enable replication = yes
    #replication period = 1d
    #replication step = 10m
    #is ephemeral node = no
STREAMCONF

    echo -e "  ${OK} stream.conf écrit dans ${STREAM_CONF}"

    # ── Restart du conteneur ──────────────────────────────────────────────────
    echo ""
    echo -e "${BOLD}>>> 9. REDÉMARRAGE DU CONTENEUR NETDATA${RESET}"
    echo "---------------------------------------------"

    cd "${NETDATA_DIR}"
    sudo ${COMPOSE_CMD} restart netdata

    sleep 5
    if sudo ${COMPOSE_CMD} ps | grep -q "netdata"; then
        echo -e "  ${OK} Conteneur redémarré avec succès"
    else
        echo -e "  ${WARN} Le conteneur ne répond plus après le restart — vérifiez les logs :"
        echo -e "       sudo docker compose -f ${NETDATA_DIR}/docker-compose.yml logs --tail=50"
    fi

else
    echo -e "  ${WARN} Conteneur non actif — stream.conf non déployé."
    echo -e "       Relancez le script ou démarrez manuellement :"
    echo -e "       sudo docker compose -f ${NETDATA_DIR}/docker-compose.yml up -d"
fi

# =============================================================================
# RÉSUMÉ FINAL
# =============================================================================
echo ""
echo -e "${BOLD}${CYAN}=============================================${RESET}"
echo -e "${BOLD}${CYAN}              RÉSUMÉ FINAL                   ${RESET}"
echo -e "${BOLD}${CYAN}=============================================${RESET}"
echo -e "  Hostname         : ${BOLD}${HOSTNAME_VAL}${RESET}"
echo -e "  Variable env     : HOSTNAME_ENV=${BOLD}${HOSTNAME_ENV}${RESET}"
echo -e "  Fichier .env     : ${NETDATA_DIR}/.env"
echo -e "  Docker Compose   : ${NETDATA_DIR}/docker-compose.yml"
echo -e "  stream.conf      : ${NETDATA_DIR}/config/stream.conf"
echo -e "  Docker           : ${OK}"
echo -e "  Netdata          : ${OK}"
echo -e "  Streaming        : ${OK} → 172.0.16.236:19999"
echo ""
echo -e "${BOLD}  Dashboard → http://$(hostname -I | awk '{print $1}'):19999${RESET}"
echo ""