#!/bin/bash

R='\033[0;31m'
G='\033[0;32m'
Y='\033[0;33m'
C='\033[0;36m'
B='\033[1;34m'
N='\033[0m'

log() {
  t=$(date +"%Y-%m-%d %H:%M:%S")
  case $1 in
    INFO) echo -e "${C}[INFO][$t]${N} $2" ;;
    SUCCESS) echo -e "${G}[SUCCESS][$t]${N} $2" ;;
    ERROR) echo -e "${R}[ERROR][$t]${N} $2" ;;
    *) echo -e "${Y}[LOG][$t]${N} $2" ;;
  esac
}

curl -s https://file.winsnip.xyz/file/uploads/Logo-winsip.sh | bash
log INFO "Starting Check-Block-Validator..."
CHAIN_NAME=".lumera"
REMOTE_RPC="https://lumera-mainnet-rpc.astrostake.xyz/status"

DIR="$HOME/$CHAIN_NAME"
PORT=$(grep -m1 -oP '^laddr = "\K[^"]+' "$DIR/config/config.toml" | cut -d ':' -f3)

[[ -z "$PORT" ]] && log ERROR "Unable to extract RPC port." && exit 1

echo -e "\n${C}╭────────────────────────────────────────────────────╮${N}"
echo -e " ${Y}Monitoring Sync Progress Validator Node Lumera...${N}"
echo -e "${C}╰────────────────────────────────────────────────────╯${N}"

while true; do
  LOCAL=$(curl -s localhost:$PORT/status | jq -r '.result.sync_info.latest_block_height')
  REMOTE=$(curl -s "$REMOTE_RPC" | jq -r '.result.sync_info.latest_block_height')

  if ! [[ "$LOCAL" =~ ^[0-9]+$ ]] || ! [[ "$REMOTE" =~ ^[0-9]+$ ]]; then
    echo -e "${R}[X] Invalid block height data. Retrying...${N}"
    sleep 5
    continue
  fi

  LEFT=$((REMOTE - LOCAL))

  printf "${B}%-15s${N} ${G}%-15s${N} ${R}%-15s${N}\n" "Node: $LOCAL" "Network: $REMOTE" "Left: $LEFT"
  sleep 5
done
