#!/bin/bash

set -e

if [ "$UID" != 0 ]; then
    echo "Error: must run this script as root (e.g. with sudo)" >&2
    exit 1
fi

if [ "$#" != 1 ] || [[ "$1" == -* ]]; then
    echo "Error: usage: $0 https://url/for/mainnet/data.mdb"
    exit 1
fi

if ! [ -e /var/lib/beldex ]; then
    echo "/var/lib/beldex does not exist; did you properly install the beldex package?"
    exit 1
fi

if ! [ -e /var/lib/beldex/lmdb ]; then
    mkdir /var/lib/beldex/lmdb
    chown _beldex:_beldex /var/lib/beldex/lmdb
fi

node_active=
ss_active=
if systemctl -q is-active beldex-node.service; then node_active=y; fi
if systemctl -q is-active beldex-storage-server.service; then ss_active=y; fi

echo "Ready to download lmdb from $1."
if [ -e /var/lib/beldex/lmdb/data.mdb ]; then
    echo "Will overwrite existing data.mdb:"
    ls -l --si /var/lib/beldex/lmdb/data.mdb
fi
if [ -n "$node_active" ]; then
    echo -n "beldex-node.service"
    if [ -n "$ss_active" ]; then echo -n " and beldex-storage-server.service"; fi
    echo " will be stopped, then restarted when the lmdb download is complete"
else
    echo "beldex-node.service is not currently running and will be left stopped.  (Do not attempt to start it or the storage server until the download is complete!)"
fi

echo

read -p "Press enter to continue, ^C to abort"

if [ -n "$node_active" ]; then
    if [ -n "$ss_active" ]; then
        systemctl stop beldex-node.service beldex-storage-server.service
    else
        systemctl stop beldex-node.service
    fi
fi

curl "$1" >/var/lib/beldex/lmdb/data.mdb

chown _beldex:_beldex /var/lib/beldex/lmdb/data.mdb
echo "Downloaded data.mdb:"
ls -l --si /var/lib/beldex/lmdb/data.mdb

if [ -n "$node_active" ]; then
    if [ -n "$ss_active" ]; then
        echo "Starting beldex-node.service, beldex-storage-server.service"
        systemctl start beldex-node.service beldex-storage-server.service
    else
        echo "Starting beldex-node.service"
        systemctl start beldex-node.service
    fi
fi
