#!/bin/bash
export DISPLAY=:0
DATADIR="/mnt/bitcoin-data/bitcoin"
DESKTOP="$HOME/Bureau/NODE.desktop"
STATUS=$(bitcoin-cli -datadir="$DATADIR" getblockchaininfo 2>&1)

if echo "$STATUS" | grep -q "Loading block index"; then
    zenity --info --title="Bitcoin Node" --text="⏳ Node en cours de chargement (reindex)..."
    exit 0
elif echo "$STATUS" | grep -q "error"; then
    sed -i "s|Icon=.*|Icon=$HOME/.icons/btc_off.png|" "$DESKTOP"
    touch "$DESKTOP"
    ACTION=$(zenity --list --title="Bitcoin Node HORS LIGNE" \
    --text="Que veux-tu faire ?" \
    --column="Action" \
    "Ouvrir le terminal" \
    "Demarrer le node")
else
    sed -i "s|Icon=.*|Icon=$HOME/.icons/btc_on.png|" "$DESKTOP"
    touch "$DESKTOP"
    ACTION=$(zenity --list --title="Bitcoin Node EN LIGNE" \
    --text="Que veux-tu faire ?" \
    --column="Action" \
    "Ouvrir le terminal" \
    "Arreter le node")
fi

if [ "$ACTION" = "Ouvrir le terminal" ]; then
    gnome-terminal -- bash -c "bitcoin-cli -datadir=$DATADIR getblockchaininfo; exec bash"

elif [ "$ACTION" = "Arreter le node" ]; then
    if zenity --question --text="Confirmer arret du node Bitcoin ?"; then
        bitcoin-cli -datadir="$DATADIR" stop
        # Attendre confirmation propre via debug.log
        timeout 120 tail -f "$DATADIR/debug.log" | grep -m 1 "Shutdown: done" > /dev/null 2>&1
        sed -i "s|Icon=.*|Icon=$HOME/.icons/btc_off.png|" "$DESKTOP"
        touch "$DESKTOP"
        zenity --info --text="🛑 Node arrêtée proprement"
    fi

elif [ "$ACTION" = "Demarrer le node" ]; then
    if zenity --question --text="Confirmer demarrage du node Bitcoin ?"; then
        bitcoind -datadir="$DATADIR" -daemon
        zenity --info --text="🚀 Node en cours de démarrage..."
    fi
fi
