#!/bin/bash

shopt -s expand_aliases

if [[ $EUID -ne 0 ]]; then
        echo "This script must be run as root" 
        exit 1
fi


if [[ "$(lsb_release -rs)" != "20.04" && "$(lsb_release -rs)" != "18.04" ]]; then
        echo "You need Ubuntu 20.04 or 18.04! It is not guaranteed that this script will work! (Detected $(lsb_release -rs))"
fi

if [[ $(nproc) -lt 2 || $(free -m | awk '/^Mem:/{print $2}') -lt 7500 ]]; then
        echo "You need at least 2 cpu cores and 8GB of RAM! I've detected $(nproc) CPUs and $(free -m | awk '/^Mem:/{print $2}') MB of RAM "

        read -p "Are you sure you want to continue? " -n 1 -r
        echo    # (optional) move to a new line
        if [[ ! $REPLY =~ ^[Yy]$ ]]
        then
                exit 1 # handle exits from shell or function but don't exit interactive shell
        fi
fi

MY_IP=$(curl -s https://api.ipify.org)
NET=mainnet
REPO=http://www.github.com/navcoin/navcoin-core
TESTNET=0
WITH_ELECTRUM=1
ADDNODE=electrum.nav.community
BRANCH=master
ROOT_PATH=$(pwd)
DOMAIN=${MY_IP}.electrum-node.nav.community

killall -9 navcoind &>/dev/null
systemctl stop navcoind
systemctl stop electrumx

while [[ "$#" -gt 0 ]]; do
	case $1 in
		--network) NET="$2"; shift ;;
		--with_electrum) WITH_ELECTRUM="$2"; shift ;;
		--domain) DOMAIN="$2"; shift ;;
		 *) echo "Unknown parameter passed: $1"; exit 1 ;;
	esac
	shift
done

echo Settings:
echo ""
echo NET=${NET}
echo WITH_ELECTRUM=${WITH_ELECTRUM}
echo ""
echo "Please wait..."
echo ""

RPCUSER=$(hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random)
RPCPASSWORD=$(hexdump -n 16 -e '4/4 "%08X" 1 "\n"' /dev/random)

if [[ "$WITH_ELECTRUM" != "0" ]] && [[ "$WITH_ELECTRUM" != "1" ]]; then
	echo "Error! --with_electrum can only be 1 or 0"
	exit 1
fi

if [[ "$NET" != "mainnet" ]]; then
	REPO="http://www.github.com/navcoin/navcoin-core"
        TESTNET=1
        ADDNODE=electrum-testnet.nav.community
        BRANCH=master
fi

echo "This script will set up a $NET Navcoin staking node! The process will take some time..."
echo 

apt-get -y update &>> ~/.install_log

function apt_install {
        apt -y install $1 &>> ~/.install_log
}

function build_libdb {
        cd ~
        NAVCOIN_ROOT=$(pwd)
        BDB_PREFIX="${NAVCOIN_ROOT}/db4"
        mkdir -p $BDB_PREFIX
        wget 'http://download.oracle.com/berkeley-db/db-4.8.30.NC.tar.gz'
        echo '12edc0df75bf9abd7f82f821795bcee50f42cb2e5f76a6a281b85732798364ef  db-4.8.30.NC.tar.gz' | sha256sum -c
        tar -xzvf db-4.8.30.NC.tar.gz
        sed -i 's/__atomic_compare_exchange/__atomic_compare_exchange_db/g' db-4.8.30.NC/dbinc/atomic.h
        cd db-4.8.30.NC/build_unix/
        ../dist/configure --enable-cxx --disable-shared --with-pic --prefix=$BDB_PREFIX --without-gui
        make install
        cd ~
}

function build_navcore {
	killall -9 navcoind
        git clone $REPO ~/navcoin-core
        cd ~/navcoin-core
        git checkout $BRANCH
        git pull
	cd depends
	make -j$(nproc) NO_QT=1
	cd ..
        ./autogen.sh
        ./configure --without-gui --disable-tests --prefix=`pwd`/depends/`uname -m`-pc-linux-gnu 
        make -j$(nproc)
        make install
}

function setup_navcore {
        mkdir -p /usr/lib/systemd/system
        cp contrib/init/navcoind.service /usr/lib/systemd/system
        mkdir -p /etc/navcoin
        cat > /etc/navcoin/navcoin.conf << EOL
rpcuser=${RPCUSER}
rpcpassword=${RPCPASSWORD}
txindex=1
nftindex=1
addressindex=1
testnet=${TESTNET}
addnode=${ADDNODE}
noonion=1
blsctmix=0
EOL
        mkdir -p /var/lib/navcoind
        ln -s /etc/navcoin/navcoin.conf /var/lib/navcoind/navcoind.conf
        ln -s /var/lib/navcoind ~/.navcoin4
        chown -R navcoin:navcoin /etc/navcoin
        chown -R navcoin:navcoin /var/lib/navcoind
        chmod -R 740 /etc/navcoin
        chmod -R 740 /var/lib/navcoind
        cat > /usr/lib/systemd/system/navcoind.service << EOL
[Unit]
Description=NavCoin's distributed currency daemon
After=network.target

[Service]
User=navcoin
Group=navcoin
Type=forking
PIDFile=/var/lib/navcoind/navcoind.pid
ExecStart=/usr/bin/navcoind -daemon -pid=/var/lib/navcoind/navcoind.pid -conf=/etc/navcoin/navcoin.conf -datadir=/var/lib/navcoind

Restart=always
RestartSec=20
PrivateTmp=true
TimeoutStopSec=600s
TimeoutStartSec=15s
StartLimitInterval=120s
StartLimitBurst=5

[Install]
WantedBy=multi-user.target
EOL
        cp `pwd`/depends/`uname -m`-pc-linux-gnu/bin/navcoind /usr/bin/navcoind
        rm /bootstrap*;systemctl stop navcoind&&cd /&&wget http://electrum.nav.community/bootstrap-txindex-addressindex.tar&&tar xvf bootstrap-txindex-addressindex.tar&&chown -R navcoin:navcoin /var/lib/navcoind;rm /bootstrap*;cd $ROOT_PATH/navcoin-core
        systemctl daemon-reload
        systemctl enable navcoind
        echo alias navcoin-cli=\"`pwd`/depends/`uname -m`-pc-linux-gnu/bin/navcoin-cli -testnet=$TESTNET -rpcuser=$RPCUSER -rpcpassword=$RPCPASSWORD\" > ~/.bashrc
	source ~/.bashrc
        systemctl start navcoind
}

echo [1/6] Creating usernames...
adduser --disabled-password --gecos "" navcoin &>> ~/.install_log
adduser --disabled-password --gecos "" electrumx &>> ~/.install_log

echo [2/6] Installing dependencies
apt_install "build-essential certbot libtool autotools-dev automake pkg-config git cmake libattr1-dev python3-dev python3-pip"

echo [3/6] Building Navcoin Core
build_navcore &>> ~/.install_log

echo [4/6] Setting up Navcoin Core
setup_navcore &>> ~/.install_log

sleep 5

function build_electrum {
        cd ~
        pip3 install setuptools
        pip3 install wheel
        pip3 install plyvel
        pip3 install aiorpcx
        git clone https://github.com/MaruCoinOfficial/x13-hash
        cd x13-hash
        python3 setup.py install
        cd ~
        git clone http://www.github.com/aguycalled/electrumx
        cd electrumx
        python3 setup.py install
        cp contrib/systemd/electrumx.service /etc/systemd/system/
        chown -R electrumx:electrumx /etc/letsencrypt
        mkdir /home/electrumx/db
        chown electrumx /home/electrumx/db
        cat > /etc/electrumx.conf << EOL
COIN=Navcoin
NET=${NET}
DB_DIRECTORY=/home/electrumx/db
DAEMON_URL=${RPCUSER}:${RPCPASSWORD}@127.0.0.1
USERNAME=electrumx
ANON_LOGS=x.x.x.x
SSL_CERTFILE=/etc/letsencrypt/live/${MY_IP}.electrum-node.nav.community/fullchain.pem
SSL_KEYFILE=/etc/letsencrypt/live/${MY_IP}.electrum-node.nav.community/privkey.pem
SERVICES=tcp://${MY_IP}:40001,ssl://${MY_IP}:40002,wss://${MY_IP}:40004
MAX_SEND=10000000
COST_SOFT_LIMIT=0
COST_HARD_LIMIT=0
EOL
        systemctl daemon-reload
        systemctl enable electrumx
        systemctl start electrumx
	(sudo crontab -l ; echo "@weekly systemctl stop electrumx && export \$(cat /etc/electrumx.conf | xargs) && sudo -u electrumx -E electrumx_compact_history; systemctl start electrumx") | sort - | uniq - | sudo crontab -
}

echo [5/6] Setting up SSL certificate
if [[ $WITH_ELECTRUM == 1 ]]; then
	certbot certonly --register-unsafely-without-email --agree-tos --standalone -d ${DOMAIN} -n &>> ~/.install_log
else
	echo [6/6] Skipping SSL certificates...
fi

echo [6/6] Installing electrum
if [[ $WITH_ELECTRUM == 1 ]]; then
	build_electrum &>> ~/.install_log
else
	echo [6/6] Skipping electrum...
fi

#while [ -n $($ROOT_PATH/navcoin-core/depends/`uname -m`-pc-linux-gnu/bin/navcoin-cli -testnet=$TESTNET -rpcuser=$RPCUSER -rpcpassword=$RPCPASSWORD getnewaddress) ]; do
while true; do 
    $ROOT_PATH/navcoin-core/depends/`uname -m`-pc-linux-gnu/bin/navcoin-cli -testnet=$TESTNET -rpcuser=$RPCUSER -rpcpassword=$RPCPASSWORD getnewaddress
    if [ $? -eq 0 ]; then 
        break
    fi

    echo Waiting for the node to be ready...
    sleep 15
done

STAKING_ADDRESS=$($ROOT_PATH/navcoin-core/depends/`uname -m`-pc-linux-gnu/bin/navcoin-cli -testnet=$TESTNET -rpcuser=$RPCUSER -rpcpassword=$RPCPASSWORD getnewaddress)
NODE_ADDRESS=${MY_IP}.electrum-node.nav.community

echo $STAKING_ADDRESS > ~/.staking_address
echo $NODE_ADDRESS > ~/.node_address

echo
echo INSTALLATION COMPLETE!
echo
echo Your staking address: $STAKING_ADDRESS
echo Your electrum node address: $NODE_ADDRESS
