#!/bin/bash

if [ -f /usr/share/lib/geth-utils/geth-utils.include.sh ]; then source /usr/share/lib/geth-utils/geth-utils.include.sh; fi
if [ -f /etc/geth-utils/geth.conf ]; then source /etc/geth-utils/geth.conf; fi
if [ "$1" = "-c" -o "$1" = "--chain" ]; then CMDLINECHAIN="$2";shift;shift; fi; _defineChain
if [ -n "$ONLYUSER" -a "`whoami`" != "$ONLYUSER" ]; then echo "Only to be called es user >$ONLYUSER<"; exit 17; fi
if [ "`whoami`" = "root" ]; then echo "Not to be called as user >root<"; exit 17; fi

GETH="geth --nousb --metrics --datadir $GETHDIR/$CHAIN -ipcpath $GETHDIR/$CHAIN/geth.ipc"
LOGFILE=$GETHDIR/$CHAIN/eth.log

_usage () {
   echo "Usage: `basename $0` [ -c CHAIN | --chain CHAIN ]"
   echo "Usage: `basename $0` [ -h | --help ]"
   echo "Usage: `basename $0` [ -v | --version ]"
}

_version () {
   echo "them-geth-utils Version $GVERSION"
}

if [ "$1" = "-h" -o "$1" = "--help" ]; then
   _usage
   exit 17
fi

if [ "$1" = "-v" -o "$1" == "--version" ]; then
   _version
   exit 17
fi

echo "Doing `basename $0` for Chain $CHAIN"

if [ $CHAIN = loc ]; then

   echo "ERROR: local chain has no peers."
   exit 17

else

   if [ \! -S $GETHDIR/$CHAIN/geth.ipc ]; then
   echo "ERROR: geth seems not to be running for chain $CHAIN on socket $GETHDIR/$CHAIN/geth.ipc."
   exit 17
   fi

   if [ -f /etc/geth-utils/net/$CHAIN/nodes ]; then
        cat /etc/geth-utils/net/$CHAIN/nodes | cut -d '#' -f 1 | egrep -v '^[ \t]*$' | while read N; do
           echo "Adding peer $N from /etc/geth-utils/net/$CHAIN/nodes to >$CHAIN test chain<" >> $LOGFILE
           echo "Adding peer $N from /etc/geth-utils/net/$CHAIN/nodes to >$CHAIN test chain<"
           echo "Calling $GETH --exec \"admin.addPeer(\\\"$N\\\")\" attach"
                         $GETH --exec "admin.addPeer(\"$N\")" attach 2>> $LOGFILE
        done
   fi

   wget -qO - ${PEERLISTURL}/peers.$CHAIN | cut -d '#' -f 1 | egrep -v '^[ \t]*$' | while read N; do
           echo "Adding peer $N from ${PEERLISTURL}/peers.$CHAIN to >$CHAIN test chain<" >> $LOGFILE
           echo "Adding peer $N from ${PEERLISTURL}/peers.$CHAIN to >$CHAIN test chain<"
           echo "Calling $GETH --exec \"admin.addPeer(\\\"$N\\\")\" attach"
                         $GETH --exec "admin.addPeer(\"$N\")" attach 2>> $LOGFILE
   done

fi
