#!/bin/bash
DATADIR="/mnt/bitcoin-data/bitcoin"
OUTPUT="/home/ubtssd/btc_status.json"

while true; do
    if bitcoin-cli -datadir="$DATADIR" getblockchaininfo > /dev/null 2>&1; then
        INFO=$(bitcoin-cli -datadir="$DATADIR" getblockchaininfo 2>/dev/null)
        MINING=$(bitcoin-cli -datadir="$DATADIR" getmininginfo 2>/dev/null)
        PEERS=$(bitcoin-cli -datadir="$DATADIR" getconnectioncount 2>/dev/null)
        MEMPOOL=$(bitcoin-cli -datadir="$DATADIR" getmempoolinfo 2>/dev/null)

        BLOCKS=$(echo "$INFO" | grep '"blocks"' | awk '{print $2}' | tr -d ',')
        PROGRESS=$(echo "$INFO" | grep '"verificationprogress"' | awk '{print $2}' | tr -d ',')
        DIFFICULTY=$(echo "$INFO" | grep '"difficulty"' | awk '{print $2}' | tr -d ',')
        HASHRATE=$(echo "$MINING" | grep '"networkhashps"' | awk '{print $2}' | tr -d ',')
        MEMPOOL_COUNT=$(echo "$MEMPOOL" | grep '"size"' | awk '{print $2}' | tr -d ',')
        MEMPOOL_MB=$(echo "$MEMPOOL" | grep '"bytes"' | awk '{print $2}' | tr -d ',')
        UPTIME=$(bitcoin-cli -datadir="$DATADIR" uptime 2>/dev/null)

        cat > "$OUTPUT" <<EOF
{
  "status": "active",
  "blocks": $BLOCKS,
  "progress": $PROGRESS,
  "difficulty": $DIFFICULTY,
  "hashrate": $HASHRATE,
  "peers": $PEERS,
  "mempool_count": $MEMPOOL_COUNT,
  "mempool_bytes": $MEMPOOL_MB,
  "uptime_seconds": $UPTIME,
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
    else
        cat > "$OUTPUT" <<EOF
{
  "status": "inactive",
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF
    fi
    sleep 60
done

