#!/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

# DEFAULTMODE=auto
DEFAULTMODE=$GETHINSTALLMODE
source /usr/share/scripts/singlestep

_usage () {
   echo "Usage: `basename $0`"
   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`"

if [ `whoami` != root ]; then
  echo "must be called as root."
  exit 17
fi

_prepare() {
    singleline apt-get update
    singleline apt-get -t sid -y install git build-essential
    # singleline apt-get -y -t buster install build-essential
    singleline apt-get -y install golang-1.19-go # needed for older versions of geth
    singleline ln -s /usr/lib/go-1.19/bin/go /usr/local/bin/go
}

_compile() {
    export GVERSION=""
    _set_git_version $GETHVERSION
    singleline git checkout $GVERSION
    singleline make geth
    #     singleline make all
    # go run build/ci.go install ./cmd/geth
    # go run build/ci.go install ./cmd/clef
}

_post () {
    if [ \! -L /usr/local/bin/geth -a -f /usr/src/go-ethereum/build/bin/geth ]; then
       singleline ln -s /usr/src/go-ethereum/build/bin/geth /usr/local/bin/geth
    fi
#    if [ \! -L /usr/local/bin/clef -a -f /usr/src/go-ethereum/build/bin/clef ]; then
#       singleline ln -s /usr/src/go-ethereum/build/bin/clef /usr/local/bin/clef
#    fi
}


echo  "=========== go-ethereum installation:"
if [ -d /usr/src/go-ethereum ]; then
    echo "go-ethereum installation seems to exist in /usr/src/go-ethereum; Just updating."
    _prepare
    doline cd /usr/src/go-ethereum
    singleline git fetch
    singleline git pull
    _compile
    _post
    singleline git checkout master
else
    echo "go-ethereum installation not yet exists in /usr/src/go-ethereum; Doing fresh install."
    _prepare
    doline cd /usr/src
    singleline git clone https://github.com/ethereum/go-ethereum
    doline cd /usr/src/go-ethereum
    _compile
    _post
    singleline git checkout master
fi

#echo "=========== porosidity installation:"
#if [ -d /usr/src/porosity ]; then
#    echo "porosity installation seems to exist in /usr/src/porosity; use gethUpdate instead"
#else
#    doline cd /usr/src
#    singleline git clone --recursive https://github.com/comaeio/porosity.git
#    doline cd /usr/src/porosity/porosity/porosity
#    singleline make
#    
#    if [ \! -L /usr/local/bin/porosity -a -f /usr/src/porosity/porosity/porosity/porosity ]; then
#       singleline ln -s /usr/src/porosity/porosity/porosity/porosity /usr/local/bin/porosity
#    fi
#fi

echo "=========== ... finished"

# echo "You may call now: gstart ..."
