#!/usr/bin/env bash

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <node ip for rpc | url for rpc> <mins buffer>"
  exit 1
fi

if ! command -v "casper-client" &> /dev/null ; then
  echo "casper-client is not installed and required. Exiting..."
  exit 1 
fi

if [[ $1 == http* ]]; then
  # Starts with http, so assume good full url
  NODE_ADDRESS="--node-address $1"
else
  NODE_ADDRESS="--node-address http://$NODE_IP:7777"
fi

BUFFER_MINS=$2

LAST_SWITCH_BLOCK=$(casper-client get-era-summary $NODE_ADDRESS | jq -r .result.era_summary.block_hash | tr -d "/n")

# Getting Timestamp and Era with one call using `@` delimiter
SB_TIMESTAMP_AND_ERA=$(casper-client get-block -b $LAST_SWITCH_BLOCK $NODE_ADDRESS | jq -r '.result.block_with_signatures.block.Version2.header | [.timestamp,.era_id] | join("@")' | tr -d "/n")

# Parsing this back into seperate variables
IFS=@ read -r SB_TIMESTAMP LAST_ERA_ID <<< "$SB_TIMESTAMP_AND_ERA"

SB_EPOCH=$(date -d "$SB_TIMESTAMP" +%s)
NOW_EPOCH=$(date +%s)

MINS_TILL_SB=$(( 120 - ((NOW_EPOCH - $SB_EPOCH) / 60) ))

if [ "$MINS_TILL_SB" -gt "$BUFFER_MINS" ]; then 
  NEXT_BUF_ERA=$(( LAST_ERA_ID + 2 ));
else 
  NEXT_BUF_ERA=$(( LAST_ERA_ID + 3 ));
fi

echo "$NEXT_BUF_ERA"
