#!/usr/bin/env zsh
set -e
echo -n "Initializing..."

case `uname -s` in

    FreeBSD)
        OS=FreeBSD
        NPROC=$(sysctl hw.ncpu | awk '{print $2}')
    ;;

    Linux)
        if [ "$(grep -Ei 'debian|buntu|mint' /etc/*release)" ]; then
            OS=Debian
            NPROC=$(nproc --all)
        else
            echo "Your distribution of Linux is not yet supported by this installation script"
            exit 1
        fi
    ;;

    *)
        echo "Unsupported OS"
        exit 1
    ;;

esac

########################################
##### mempool installation options #####
########################################

# tor onion and clearnet hostname
TOR_INSTALL=ON
CERTBOT_INSTALL=ON

# install 4 network daemons
BITCOIN_INSTALL=ON
BISQ_INSTALL=ON
ELEMENTS_INSTALL=ON
CLN_INSTALL=ON

# install UNFURL
UNFURL_INSTALL=ON

# configure 4 network instances
BITCOIN_MAINNET_ENABLE=ON
BITCOIN_MAINNET_MINFEE_ENABLE=ON
BITCOIN_TESTNET_ENABLE=ON
BITCOIN_SIGNET_ENABLE=ON
BITCOIN_MAINNET_LIGHTNING_ENABLE=ON
BITCOIN_TESTNET_LIGHTNING_ENABLE=ON
BITCOIN_SIGNET_LIGHTNING_ENABLE=ON
BISQ_MAINNET_ENABLE=ON
ELEMENTS_LIQUID_ENABLE=ON
ELEMENTS_LIQUIDTESTNET_ENABLE=ON

# enable lightmode and disable compaction to fit on 1TB SSD drive
BITCOIN_ELECTRS_INSTALL=ON
BITCOIN_ELECTRS_LIGHT_MODE=ON
BITCOIN_ELECTRS_COMPACTION=OFF
ELEMENTS_ELECTRS_INSTALL=ON
ELEMENTS_ELECTRS_LIGHT_MODE=ON
ELEMENTS_ELECTRS_COMPACTION=OFF

# automaitcally configure firewall
FIREWALL_CONFIGURE=ON

############
# probe OS #
############

HOSTNAME=$(hostname)

# get newest zpool if using zfs
ZPOOL=""
[ "${OS}" = FreeBSD ] && ZPOOL=$(zpool list -H|head -1|cut -f 1)

MD5=md5sum
[ "${OS}" = FreeBSD ] && MD5=md5

##################################################
##### P2P / RPC / HTTP network communication #####
##################################################

# used for bisq and firewall configuration
BITCOIN_MAINNET_P2P_HOST=127.0.0.1
BITCOIN_MAINNET_P2P_PORT=8333
# used for RPC communication
BITCOIN_MAINNET_RPC_HOST=127.0.0.1
BITCOIN_MAINNET_RPC_PORT=8332
# generate random hex string
BITCOIN_RPC_USER=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
BITCOIN_RPC_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')

# used for firewall configuration
BITCOIN_TESTNET_P2P_HOST=127.0.0.1
BITCOIN_TESTNET_P2P_PORT=18333
# used for RPC communication
BITCOIN_TESTNET_RPC_HOST=127.0.0.1
BITCOIN_TESTNET_RPC_PORT=18332

# used for firewall configuration
BITCOIN_SIGNET_P2P_HOST=127.0.0.1
BITCOIN_SIGNET_P2P_PORT=18333
# used for RPC communication
BITCOIN_SIGNET_RPC_HOST=127.0.0.1
BITCOIN_SIGNET_RPC_PORT=18332
# generate random hex string
BITCOIN_SIGNET_RPC_USER=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
BITCOIN_SIGNET_RPC_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')

# used by bisq to receive notifications from bitcoin about new blocks
BISQ_BLOCKNOTIFY_HOST=127.0.0.1
BISQ_BLOCKNOTIFY_PORT=5120

# used for firewall configuration
ELEMENTS_LIQUID_P2P_HOST=127.0.0.1
ELEMENTS_LIQUID_P2P_PORT=7042
# used for RPC communication
ELEMENTS_LIQUID_RPC_HOST=127.0.0.1
ELEMENTS_LIQUID_RPC_PORT=7041
# generate random hex string
ELEMENTS_RPC_USER=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
ELEMENTS_RPC_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')

# set either socket or TCP host/port, not both
#ELECTRS_MAINNET_HTTP_SOCK=/tmp/bitcoin.mainnet.electrs
ELECTRS_MAINNET_HTTP_HOST=127.0.0.1
ELECTRS_MAINNET_HTTP_PORT=3000

# set either socket or TCP host/port, not both
#ELECTRS_LIQUID_HTTP_SOCK=/tmp/elements.liquid.electrs
ELECTRS_LIQUID_HTTP_HOST=127.0.0.1
ELECTRS_LIQUID_HTTP_PORT=3001

# set either socket or TCP host/port, not both
#ELECTRS_TESTNET_HTTP_SOCK=/tmp/bitcoin.testnet.electrs
ELECTRS_TESTNET_HTTP_HOST=127.0.0.1
ELECTRS_TESTNET_HTTP_PORT=3002

# set either socket or TCP host/port, not both
#ELECTRS_SIGNET_HTTP_SOCK=/tmp/bitcoin.testnet.electrs
ELECTRS_SIGNET_HTTP_HOST=127.0.0.1
ELECTRS_SIGNET_HTTP_PORT=3003

# set either socket or TCP host/port, not both
#ELECTRS_LIQUIDTESTNET_HTTP_SOCK=/tmp/bitcoin.testnet.electrs
ELECTRS_LIQUIDTESTNET_HTTP_HOST=127.0.0.1
ELECTRS_LIQUIDTESTNET_HTTP_PORT=3004

# set either socket or TCP host/port, not both
#MEMPOOL_MAINNET_HTTP_SOCK=/tmp/bitcoin.mainnet.mempool
MEMPOOL_MAINNET_HTTP_HOST=127.0.0.1
MEMPOOL_MAINNET_HTTP_PORT=8999

# set either socket or TCP host/port, not both
#MEMPOOL_LIQUID_HTTP_SOCK=/tmp/elements.liquid.mempool
MEMPOOL_LIQUID_HTTP_HOST=127.0.0.1
MEMPOOL_LIQUID_HTTP_PORT=8998

# set either socket or TCP host/port, not both
#MEMPOOL_TESTNET_HTTP_SOCK=/tmp/bitcoin.testnet.mempool
MEMPOOL_TESTNET_HTTP_HOST=127.0.0.1
MEMPOOL_TESTNET_HTTP_PORT=8997

# set either socket or TCP host/port, not both
#MEMPOOL_BISQ_HTTP_SOCK=/tmp/bitcoin.bisq.mempool
MEMPOOL_BISQ_HTTP_HOST=127.0.0.1
MEMPOOL_BISQ_HTTP_PORT=8996

# set either socket or TCP host/port, not both
#MEMPOOL_SIGNET_HTTP_SOCK=/tmp/bitcoin.bisq.mempool
MEMPOOL_SIGNET_HTTP_HOST=127.0.0.1
MEMPOOL_SIGNET_HTTP_PORT=8995

# set either socket or TCP host/port, not both
#MEMPOOL_LIQUIDTESTNET_HTTP_SOCK=/tmp/bitcoin.bisq.mempool
MEMPOOL_LIQUIDTESTNET_HTTP_HOST=127.0.0.1
MEMPOOL_LIQUIDTESTNET_HTTP_PORT=8994

##### OS options, should be automatically detected

case $OS in
    FreeBSD)
        ROOT_USER=root
        ROOT_GROUP=wheel
        ROOT_HOME=/root
        TOR_CONFIGURATION=/usr/local/etc/tor/torrc
        TOR_RESOURCES=/var/db/tor
        TOR_PKG=tor
        TOR_USER=_tor
        TOR_GROUP=_tor
        NGINX_USER=www
        NGINX_GROUP=www
        NGINX_ETC_FOLDER=/usr/local/etc/nginx
        NGINX_CONFIGURATION=/usr/local/etc/nginx/nginx.conf
        CERTBOT_PKG=py39-certbot
        CLN_PKG=c-lightning
    ;;

    Debian)
        ROOT_USER=root
        ROOT_GROUP=root
        ROOT_HOME=/root
        TOR_CONFIGURATION=/etc/tor/torrc
        TOR_RESOURCES=/var/lib/tor
        TOR_PKG=tor
        TOR_USER=debian-tor
        TOR_GROUP=debian-tor
        CERTBOT_PKG=python3-certbot-nginx
        NGINX_USER=www-data
        NGINX_GROUP=www-data
        NGINX_ETC_FOLDER=/etc/nginx
        NGINX_CONFIGURATION=/etc/nginx/nginx.conf
    ;;
esac

# where systemd services get installed
DEBIAN_SERVICE_HOME=/etc/systemd/system
# where environment variables for services are set
DEBIAN_ENV_HOME=/etc/default
# where rc.d scripts live
FREEBSD_SERVICE_HOME=/usr/local/etc/rc.d

# mysql data folder and user/group
MYSQL_HOME=/mysql
MYSQL_USER=mysql
MYSQL_GROUP=mysql

# mempool mysql user/password
MEMPOOL_MAINNET_USER='mempool'
MEMPOOL_TESTNET_USER='mempool_testnet'
MEMPOOL_SIGNET_USER='mempool_signet'
MEMPOOL_MAINNET_LIGHTNING_USER='mempool_mainnet_lightning'
MEMPOOL_TESTNET_LIGHTNING_USER='mempool_testnet_lightning'
MEMPOOL_SIGNET_LIGHTNING_USER='mempool_signet_lightning'
MEMPOOL_LIQUID_USER='mempool_liquid'
MEMPOOL_LIQUIDTESTNET_USER='mempool_liquidtestnet'
MEMPOOL_BISQ_USER='mempool_bisq'
# generate random hex string
MEMPOOL_MAINNET_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_TESTNET_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_SIGNET_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_MAINNET_LIGHTNING_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_TESTNET_LIGHTNING_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_SIGNET_LIGHTNING_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_LIQUID_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_LIQUIDTESTNET_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')
MEMPOOL_BISQ_PASS=$(head -150 /dev/urandom | ${MD5} | awk '{print $1}')

# mempool data folder and user/group
MEMPOOL_HOME=/mempool
MEMPOOL_USER=mempool
MEMPOOL_GROUP=mempool
MEMPOOL_MYSQL_CREDENTIALS="${MEMPOOL_HOME}/.mysql_credentials"
# name of Tor hidden service in torrc
MEMPOOL_TOR_HS=mempool

# bitcoin user/group
BITCOIN_USER=bitcoin
BITCOIN_GROUP=bitcoin
# bitcoin core data folder, needs about 300GB
BITCOIN_HOME=/bitcoin

# bitcoin testnet data
BITCOIN_TESTNET_DATA=${BITCOIN_HOME}/testnet3
# bitcoin testnet data
BITCOIN_SIGNET_DATA=${BITCOIN_HOME}/signet

# bitcoin electrs source/binaries
BITCOIN_ELECTRS_HOME=${BITCOIN_HOME}/electrs

# electrs database root
ELECTRS_DATA_ROOT=/electrs
# bitcoin electrs data, needs about 350GB, and uses double that during compaction
ELECTRS_MAINNET_ZPOOL=${ZPOOL}
ELECTRS_MAINNET_DATA=${ELECTRS_DATA_ROOT}/mainnet
# bitcoin testnet electrs database, only a few GB
ELECTRS_TESTNET_ZPOOL=${ZPOOL}
ELECTRS_TESTNET_DATA=${ELECTRS_DATA_ROOT}/testnet
# bitcoin signet electrs database, only a few GB
ELECTRS_SIGNET_ZPOOL=${ZPOOL}
ELECTRS_SIGNET_DATA=${ELECTRS_DATA_ROOT}/signet
# liquid electrs data, needs about 5GB
ELECTRS_LIQUID_ZPOOL=${ZPOOL}
ELECTRS_LIQUID_DATA=${ELECTRS_DATA_ROOT}/liquid
# liquid electrs data, needs about 5GB
ELECTRS_LIQUIDTESTNET_ZPOOL=${ZPOOL}
ELECTRS_LIQUIDTESTNET_DATA=${ELECTRS_DATA_ROOT}/liquidtestnet

# Core Lightning user/group
CLN_USER=cln
CLN_GROUP=cln
# Core Lightning home folder
CLN_HOME=/cln

# bisq user/group
BISQ_USER=bisq
BISQ_GROUP=bisq
# bisq home folder, needs about 1GB
BISQ_HOME=/bisq
# tor HS folder
BISQ_TOR_HS=bisq

# liquid user/group
ELEMENTS_USER=elements
ELEMENTS_GROUP=elements
# liquid home/data/blockchain folder, needs about 10GB
ELEMENTS_HOME=/elements
# electrs db top-level
ELECTRS_HOME=/electrs
# elements electrs source/binaries
ELEMENTS_ELECTRS_HOME=${ELEMENTS_HOME}/electrs
# tor HS folder
LIQUID_TOR_HS=liquid

# minfee user/group
MINFEE_USER=minfee
MINFEE_GROUP=minfee
# minfee core data folder, needs about 30GB
MINFEE_HOME=/minfee

##### git repo settings, shouldn't need changing

MEMPOOL_REPO_URL=https://github.com/mempool/mempool
MEMPOOL_REPO_NAME=mempool
MEMPOOL_REPO_BRANCH=master
MEMPOOL_LATEST_RELEASE=master

BITCOIN_REPO_URL=https://github.com/bitcoin/bitcoin
BITCOIN_REPO_NAME=bitcoin
BITCOIN_REPO_BRANCH=master
#BITCOIN_LATEST_RELEASE=$(curl -s https://api.github.com/repos/bitcoin/bitcoin/releases/latest|grep tag_name|head -1|cut -d '"' -f4)
BITCOIN_LATEST_RELEASE=v25.0
echo -n '.'

BISQ_REPO_URL=https://github.com/bisq-network/bisq
BISQ_REPO_NAME=bisq
BISQ_REPO_BRANCH=master
#BISQ_LATEST_RELEASE=$(curl -s https://api.github.com/repos/bisq-network/bisq/releases/latest|grep tag_name|head -1|cut -d '"' -f4)
BISQ_LATEST_RELEASE=master
echo -n '.'

UNFURL_REPO_URL=https://github.com/mempool/mempool
UNFURL_REPO_NAME=unfurl
UNFURL_REPO_BRANCH=master
#UNFURL_LATEST_RELEASE=$(curl -s https://api.github.com/repos/mempool/mempool/releases/latest|grep tag_name|head -1|cut -d '"' -f4)
UNFURL_LATEST_RELEASE=master
echo -n '.'

ELEMENTS_REPO_URL=https://github.com/ElementsProject/elements
ELEMENTS_REPO_NAME=elements
ELEMENTS_REPO_BRANCH=master
#ELEMENTS_LATEST_RELEASE=$(curl -s https://api.github.com/repos/ElementsProject/elements/releases/latest|grep tag_name|head -1|cut -d '"' -f4)
ELEMENTS_LATEST_RELEASE=elements-22.1.1
echo -n '.'

BITCOIN_ELECTRS_REPO_URL=https://github.com/mempool/electrs
BITCOIN_ELECTRS_REPO_NAME=electrs
BITCOIN_ELECTRS_REPO_BRANCH=mempool
BITCOIN_ELECTRS_LATEST_RELEASE=mempool

ELEMENTS_ELECTRS_REPO_URL=https://github.com/mempool/electrs
ELEMENTS_ELECTRS_REPO_NAME=electrs
ELEMENTS_ELECTRS_REPO_BRANCH=mempool
ELEMENTS_ELECTRS_LATEST_RELEASE=mempool

LIQUID_ASSET_REGISTRY_DB_URL=https://github.com/blockstream/asset_registry_db
LIQUID_ASSET_REGISTRY_DB_NAME=asset_registry_db
LIQUIDTESTNET_ASSET_REGISTRY_DB_URL=https://github.com/blockstream/asset_registry_testnet_db
LIQUIDTESTNET_ASSET_REGISTRY_DB_NAME=asset_registry_testnet_db

#######################
##### OS packages #####
#######################

# packages needed for mempool ecosystem
DEBIAN_PKG=()
DEBIAN_PKG+=(zsh vim curl screen openssl python3 dialog cron)
DEBIAN_PKG+=(build-essential git git-lfs clang cmake jq)
DEBIAN_PKG+=(autotools-dev autoconf automake pkg-config bsdmainutils)
DEBIAN_PKG+=(libevent-dev libdb-dev libssl-dev libtool autotools-dev)
DEBIAN_PKG+=(libboost-system-dev libboost-filesystem-dev libboost-chrono-dev libboost-test-dev libboost-thread-dev)
DEBIAN_PKG+=(nodejs npm mariadb-server nginx-core python3-certbot-nginx rsync ufw)
DEBIAN_PKG+=(geoipupdate)

DEBIAN_UNFURL_PKG=()
DEBIAN_UNFURL_PKG+=(cups chromium-bsu libatk1.0 libatk-bridge2.0 libxkbcommon-dev libxcomposite-dev)
DEBIAN_UNFURL_PKG+=(libxdamage-dev libxrandr-dev libgbm-dev libpango1.0-dev libasound-dev)

# packages needed for mempool ecosystem
FREEBSD_PKG=()
FREEBSD_PKG+=(zsh sudo git git-lfs screen curl wget calc neovim)
FREEBSD_PKG+=(openssh-portable py39-pip rust llvm10 jq base64 libzmq4)
FREEBSD_PKG+=(boost-libs autoconf automake gmake gcc libevent libtool pkgconf)
FREEBSD_PKG+=(nginx rsync py39-certbot-nginx mariadb105-server keybase)
FREEBSD_PKG+=(geoipupdate)

FREEBSD_UNFURL_PKG=()
FREEBSD_UNFURL_PKG+=(nvidia-driver-470 chromium xinit xterm twm ja-sourcehansans-otf)
FREEBSD_UNFURL_PKG+=(zh-sourcehansans-sc-otf ko-aleefonts-ttf lohit tlwg-ttf)

#############################
##### utility functions #####
#############################

osSudo()
{
    SUDO_USER=$1
    shift
    case $OS in
        FreeBSD)
            sudo -H -i -u "${SUDO_USER}" $*
        ;;
        Debian)
            sudo -H -i -u "${SUDO_USER}" $*
        ;;
    esac
}

osPackageUpdate()
{
    echo "[*] Updating OS sources"
    case $OS in
        FreeBSD)
            pkg update
        ;;
        Debian)
            osSudo "${ROOT_USER}" DEBIAN_FRONTEND=noninteractive apt-get update -q
        ;;
    esac
}

osPackageUpgrade()
{
    echo "[*] Upgrading OS packages $*"
    case $OS in
        FreeBSD)
            pkg upgrade -y $*
        ;;
        Debian)
            osSudo "${ROOT_USER}" DEBIAN_FRONTEND=noninteractive apt-get upgrade -qq -y $*
        ;;
    esac
}

osPackageInstall()
{
    echo "[*] Installing OS packages $*"
    case $OS in
        FreeBSD)
            pkg install -y $*
        ;;
        Debian)
            osSudo "${ROOT_USER}" DEBIAN_FRONTEND=noninteractive apt-get install -qq -y $*
        ;;
    esac
}

osPackageInstallAll()
{
    case $OS in
        FreeBSD)
            osPackageInstall ${FREEBSD_PKG[@]}
        ;;
        Debian)
            osPackageInstall ${DEBIAN_PKG[@]}
        ;;
    esac
}

# osUserCreate username home_directory main_groupname [additional_group]
osUserCreate()
{
    case $OS in
        FreeBSD)
            # pw useradd -d /mempool -g mempool [-G additional_group] -n mampool
            if [ $# -eq 3 ] ; then
                osSudo "${ROOT_USER}" pw useradd -d "$2" -g "$3" -n "$1"
            elif [ $# -eq 4 ]; then
                osSudo "${ROOT_USER}" pw useradd -d "$2" -g "$3" -G "$4" -n "$1"
            else
                echo "Illegal number of parameters"
                exit 1
           fi
        ;;
        Debian)
            # useradd -d /mempool -g mempool [-G additional_group] mempool
            if [ $# -eq 3 ] ; then
                osSudo "${ROOT_USER}" useradd -d "$2" -g "$3" "$1"
            elif [ $# -eq 4 ]; then
                osSudo "${ROOT_USER}" useradd -d "$2" -g "$3" -G "$4" "$1"
            else
                echo "Illegal number of parameters"
                exit 1
           fi
        ;;
    esac
}

osGroupCreate()
{
    case $OS in
        FreeBSD)
            osSudo "${ROOT_USER}" pw groupadd $*
        ;;
        Debian)
            osSudo "${ROOT_USER}" groupadd $*
        ;;
    esac
}

osCertbotDryRun()
{
    if [ ! -z "${HOSTNAME}" ];then
        case $OS in
            FreeBSD)
                osPackageInstall "${FREEBSD_PKG_CERTBOT}"
            ;;
            Debian)
                osPackageInstall "${DEBIAN_PKG_CERTBOT}"
            ;;
        esac

        certbot certonly --dry-run --standalone --agree-tos --register-unsafely-without-email -d "${HOSTNAME}"
    fi
}

zfsCreateFilesystems()
{
    zfs create -o "mountpoint=/backup" "${ZPOOL}/backup"

    zfs create -o "mountpoint=${ELEMENTS_HOME}" "${ZPOOL}/elements"
    zfs create -o "mountpoint=${BITCOIN_HOME}" "${ZPOOL}/bitcoin"
    zfs create -o "mountpoint=${MINFEE_HOME}" "${ZPOOL}/minfee"
    zfs create -o "mountpoint=${ELECTRS_HOME}" "${ZPOOL}/electrs"
    zfs create -o "mountpoint=${MEMPOOL_HOME}" "${ZPOOL}/mempool"
    zfs create -o "mountpoint=${MYSQL_HOME}" "${ZPOOL}/mysql"

    zfs create -o "mountpoint=${BITCOIN_ELECTRS_HOME}" "${ZPOOL}/bitcoin/electrs"

    zfs create -o "mountpoint=${ELEMENTS_HOME}/liquidv1" "${ZPOOL}/elements/liquidv1"
    zfs create -o "mountpoint=${ELEMENTS_ELECTRS_HOME}" "${ZPOOL}/elements/electrs"

    # create /bitcoin/socket with custom ACL for electrs unix sockets
    zfs create -o "mountpoint=${BITCOIN_HOME}/socket" "${ZPOOL}/bitcoin/socket"

    # create /elements/socket with custom ACL for electrs unix sockets
    zfs create -o "mountpoint=${ELEMENTS_HOME}/socket" "${ZPOOL}/elements/socket"

    # Bitcoin Mainnet
    if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
        for folder in chainstate indexes blocks
        do
            zfs create -o "mountpoint=${BITCOIN_HOME}/${folder}" "${ZPOOL}/bitcoin/${folder}"
        done
    fi

    # Bitcoin Testnet
    if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${BITCOIN_TESTNET_DATA}" "${ZPOOL}/bitcoin/testnet"
        for folder in chainstate indexes blocks
        do
            zfs create -o "mountpoint=${BITCOIN_TESTNET_DATA}/${folder}" "${ZPOOL}/bitcoin/testnet/${folder}"
        done
    fi

    # Bitcoin Signet
    if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${BITCOIN_SIGNET_DATA}" "${ZPOOL}/bitcoin/signet"
        for folder in chainstate indexes blocks
        do
            zfs create -o "mountpoint=${BITCOIN_SIGNET_DATA}/${folder}" "${ZPOOL}/bitcoin/signet/${folder}"
        done
    fi

    # electrs mainnet data
    if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${ELECTRS_MAINNET_DATA}" "${ELECTRS_MAINNET_ZPOOL}/electrs/mainnet"
        for folder in cache history txstore
        do
            zfs create -o "mountpoint=${ELECTRS_MAINNET_DATA}/newindex/${folder}" "${ELECTRS_MAINNET_ZPOOL}/electrs/mainnet/${folder}"
        done
    fi

    # electrs testnet data
    if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${ELECTRS_TESTNET_DATA}" "${ELECTRS_TESTNET_ZPOOL}/electrs/testnet"
        for folder in cache history txstore
        do
            zfs create -o "mountpoint=${ELECTRS_TESTNET_DATA}/newindex/${folder}" "${ELECTRS_TESTNET_ZPOOL}/electrs/testnet/${folder}"
        done
    fi

    # electrs signet data
    if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${ELECTRS_SIGNET_DATA}" "${ELECTRS_SIGNET_ZPOOL}/electrs/signet"
        for folder in cache history txstore
        do
            zfs create -o "mountpoint=${ELECTRS_SIGNET_DATA}/newindex/${folder}" "${ELECTRS_SIGNET_ZPOOL}/electrs/signet/${folder}"
        done
    fi

    # electrs liquid data
    if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${ELECTRS_LIQUID_DATA}" "${ELECTRS_LIQUID_ZPOOL}/electrs/liquid"
        for folder in cache history txstore
        do
            zfs create -o "mountpoint=${ELECTRS_LIQUID_DATA}/newindex/${folder}" "${ELECTRS_LIQUID_ZPOOL}/electrs/liquid/${folder}"
        done
    fi

    # electrs liquidtestnet data
    if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
        zfs create -o "mountpoint=${ELECTRS_LIQUIDTESTNET_DATA}" "${ELECTRS_LIQUIDTESTNET_ZPOOL}/electrs/liquidtestnet"
        for folder in cache history txstore
        do
            zfs create -o "mountpoint=${ELECTRS_LIQUIDTESTNET_DATA}/newindex/${folder}" "${ELECTRS_LIQUIDTESTNET_ZPOOL}/electrs/liquidtestnet/${folder}"
        done
    fi

    if [ "${CLN_INSTALL}" = ON ];then
        zfs create -o "mountpoint=${CLN_HOME}" "${ZPOOL}/cln"
    fi

    if [ "${BISQ_INSTALL}" = ON ];then
        zfs create -o "mountpoint=${BISQ_HOME}" "${ZPOOL}/bisq"
    fi
}

ext4CreateDir()
{
    mkdir -p "/backup" "${ELEMENTS_HOME}" "${BITCOIN_HOME}" "${MINFEE_HOME}" "${ELECTRS_HOME}" "${MEMPOOL_HOME}" "${MYSQL_HOME}" "${BITCOIN_ELECTRS_HOME}" "${ELEMENTS_HOME}/liquidv1" "${ELEMENTS_ELECTRS_HOME}"

    # Bitcoin Mainnet
    if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
        for folder in chainstate indexes blocks
        do
            mkdir -p "${BITCOIN_HOME}/${folder}"
        done
    fi

    # Bitcoin Testnet
    if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
        mkdir -p "${BITCOIN_TESTNET_DATA}"
        for folder in chainstate indexes blocks
        do
            mkdir -p "${BITCOIN_TESTNET_DATA}/${folder}"
        done
    fi

    # Bitcoin Signet
    if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
        mkdir -p "${BITCOIN_SIGNET_DATA}"
        for folder in chainstate indexes blocks
        do
            mkdir -p "${BITCOIN_SIGNET_DATA}/${folder}"
        done
    fi

    # electrs mainnet data
    if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
        mkdir -p "${ELECTRS_MAINNET_DATA}"
        for folder in cache history txstore
        do
            mkdir -p "${ELECTRS_MAINNET_DATA}/newindex/${folder}"
        done
    fi

    # electrs testnet data
    if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
        mkdir -p "${ELECTRS_TESTNET_DATA}"
        for folder in cache history txstore
        do
            mkdir -p "${ELECTRS_TESTNET_DATA}/newindex/${folder}"
        done
    fi

    # electrs signet data
    if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
        mkdir -p "${ELECTRS_SIGNET_DATA}"
        for folder in cache history txstore
        do
            mkdir -p "${ELECTRS_SIGNET_DATA}/newindex/${folder}"
        done
    fi

    # electrs liquid data
    if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
        mkdir -p "${ELECTRS_LIQUID_DATA}"
        for folder in cache history txstore
        do
            mkdir -p "${ELECTRS_LIQUID_DATA}/newindex/${folder}"
        done
    fi

    # electrs liquidtestnet data
    if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
        mkdir -p "${ELECTRS_LIQUIDTESTNET_DATA}"
        for folder in cache history txstore
        do
            mkdir -p "${ELECTRS_LIQUIDTESTNET_DATA}/newindex/${folder}"
        done
    fi

    if [ "${CLN_INSTALL}" = ON ];then
        mkdir -p "${CLN_HOME}"
    fi

    if [ "${BISQ_INSTALL}" = ON ];then
        mkdir -p "${BISQ_HOME}"
    fi
}


##### Perform sanity checks before trying anything

# what OS running, what FS partitions, etc.
# how much free disk space available?
# is something listening on port 80 already?
# is nginx or apache running?

##### Determine what actually needs to be installed

# does bitcoin exist?

##########
# dialog #
##########

: ${DIALOG=dialog}

: ${DIALOG_OK=0}
: ${DIALOG_CANCEL=1}
: ${DIALOG_HELP=2}
: ${DIALOG_EXTRA=3}
: ${DIALOG_ITEM_HELP=4}
: ${DIALOG_ESC=255}

: ${SIG_OFFNE=0}
: ${SIG_HUP=1}
: ${SIG_INT=2}
: ${SIG_QUIT=3}
: ${SIG_KILL=9}
: ${SIG_TERM=15}

input=`tempfile 2>/dev/null` || input=/tmp/input$$
output=`tempfile 2>/dev/null` || output=/tmp/test$$
trap "rm -f $input $output" $SIG_OFFNE $SIG_HUP $SIG_INT $SIG_TRAP $SIG_TERM

DIALOG_ERROR=254
export DIALOG_ERROR

backtitle="Mempool Fullnode Installer"
title="Mempool Fullnode Installer"
returncode=0

#################
# dialog part 1 #
#################

$CUT >$input <<-EOF
Tor:Enable Tor v3 HS Onion:ON
Mainnet:Enable Bitcoin Mainnet:ON
Mainnet-Minfee:Enable Bitcoin Mainnet Minfee:ON
LN-Mainnet:Enable Bitcoin Mainnet Lightning:ON
LN-Testnet:Enable Bitcoin Testnet Lightning:ON
LN-Signet:Enable Bitcoin Signet Lightning:ON
Testnet:Enable Bitcoin Testnet:ON
Signet:Enable Bitcoin Signet:ON
Liquid:Enable Elements Liquid:ON
Liquidtestnet:Enable Elements Liquidtestnet:ON
CoreLN:Enable Core Lightning:ON
Bisq:Enable Bisq:ON
Unfurl:Enable Unfurl:ON
EOF

cat $input | sed -e 's/^/"/' -e 's/:/" "/g' -e 's/$/"/' >$output
cat $output >$input

$DIALOG --backtitle "${backtitle}" \
        --title "${title}" "$@" \
        --checklist "Toggle the features below to configure your fullnode:\n" \
        20 80 10 \
        --file $input 2> $output

retval=$?

tempfile=$output
if [ $retval != $DIALOG_OK ];then
    echo "Installation aborted."
    exit 1
fi

if grep Tor $tempfile >/dev/null 2>&1;then
    TOR_INSTALL=ON
else
    TOR_INSTALL=OFF
fi

if grep Mainnet $tempfile >/dev/null 2>&1;then
    BITCOIN_MAINNET_ENABLE=ON
else
    BITCOIN_MAINNET_ENABLE=OFF
fi

if grep Mainnet-Minfee $tempfile >/dev/null 2>&1;then
    BITCOIN_MAINNET_MINFEE_ENABLE=ON
else
    BITCOIN_MAINNET_MINFEE_ENABLE=OFF
fi

if grep Testnet $tempfile >/dev/null 2>&1;then
    BITCOIN_TESTNET_ENABLE=ON
else
    BITCOIN_TESTNET_ENABLE=OFF
fi

if grep Signet $tempfile >/dev/null 2>&1;then
    BITCOIN_SIGNET_ENABLE=ON
else
    BITCOIN_SIGNET_ENABLE=OFF
fi

if [ "${BITCOIN_MAINNET_ENABLE}" = ON -o "${BITCOIN_MAINNET_MINFEE_ENABLE}" = ON -o "${BITCOIN_TESTNET_ENABLE}" = ON -o "${BITCOIN_SIGNET_ENABLE}" = ON ];then
    BITCOIN_INSTALL=ON
else
    BITCOIN_INSTALL=OFF
fi

if grep LN-Mainnet $tempfile >/dev/null 2>&1;then
    BITCOIN_MAINNET_LIGHTNING_ENABLE=ON
else
    BITCOIN_MAINNET_LIGHTNING_ENABLE=OFF
fi

if grep LN-Testnet $tempfile >/dev/null 2>&1;then
    BITCOIN_TESTNET_LIGHTNING_ENABLE=ON
else
    BITCOIN_TESTNET_LIGHTNING_ENABLE=OFF
fi

if grep LN-Signet $tempfile >/dev/null 2>&1;then
    BITCOIN_SIGNET_LIGHTNING_ENABLE=ON
else
    BITCOIN_SIGNET_LIGHTNING_ENABLE=OFF
fi

if grep Liquid $tempfile >/dev/null 2>&1;then
    ELEMENTS_LIQUID_ENABLE=ON
else
    ELEMENTS_LIQUID_ENABLE=OFF
fi

if grep Liquidtestnet $tempfile >/dev/null 2>&1;then
    ELEMENTS_LIQUIDTESTNET_ENABLE=ON
else
    ELEMENTS_LIQUIDTESTNET_ENABLE=OFF
fi

if [ "${ELEMENTS_LIQUID_ENABLE}" = ON -o "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
    ELEMENTS_INSTALL=ON
else
    ELEMENTS_INSTALL=OFF
fi

if grep CoreLN $tempfile >/dev/null 2>&1;then
    CLN_INSTALL=ON
else
    CLN_INSTALL=OFF
fi

if [ "${BITCOIN_MAINNET_ENABLE}" = ON -o "${BITCOIN_TESTNET_ENABLE}" = ON -o "${BITCOIN_SIGNET_ENABLE}" = ON ];then
    BITCOIN_ELECTRS_INSTALL=ON
else
    BITCOIN_ELECTRS_INSTALL=OFF
fi

if [ "${ELEMENTS_LIQUID_ENABLE}" = ON -o "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
    ELEMENTS_ELECTRS_INSTALL=ON
else
    ELEMENTS_ELECTRS_INSTALL=OFF
fi

if grep Bisq $tempfile >/dev/null 2>&1;then
    BISQ_INSTALL=ON
    BISQ_MAINNET_ENABLE=ON
else
    BISQ_INSTALL=OFF
    BISQ_MAINNET_ENABLE=OFF
fi

if grep Unfurl $tempfile >/dev/null 2>&1;then
    UNFURL_INSTALL=ON
else
    UNFURL_INSTALL=OFF
fi

##################
## dialog part 2 #
##################
#
#$DIALOG --cr-wrap \
#        --title "INPUT BOX" --clear \
#        --inputbox "$@" \
#"Enter the FQDN hostname for obtaining an SSL certificate using Certbot:" 0 0 "${HOSTNAME}" 2> $tempfile
#HOSTNAME=$(cat $tempfile)
#
##################
## dialog part 3 #
##################
#
##   --form text height width formheight
##   [ label y x item y x flen ilen ]
#    #"BISQ_BLOCKNOTIFY_HOST"             0 1 "${BISQ_BLOCKNOTIFY_HOST}"              0 30 0 0 \
#
#$DIALOG --ok-label "Submit" \
#    --backtitle "$backtitle" "$@" \
#    --form "Your fullnode will be installed as follows:" 0 0 0 \
#    "BISQ_LATEST_RELEASE"               1 1 "${BISQ_LATEST_RELEASE}"                1 35 35 0 \
#    "BISQ_REPO_BRANCH"                  2 1 "${BISQ_REPO_BRANCH}"                   2 35 35 0 \
#    "BISQ_REPO_NAME"                    3 1 "${BISQ_REPO_NAME}"                     3 35 35 0 \
#    "BISQ_REPO_URL"                     4 1 "${BISQ_REPO_URL}"                      4 35 35 0 \
#    "BITCOIN_ELECTRS_LATEST_RELEASE"    5 1 "${BITCOIN_ELECTRS_LATEST_RELEASE}"    5 35 35 0 \
#    "BITCOIN_ELECTRS_LIGHT_MODE"        6 1 "${BITCOIN_ELECTRS_LIGHT_MODE}"        6 35 35 0 \
#    "BITCOIN_ELECTRS_REPO_BRANCH"       7 1 "${BITCOIN_ELECTRS_REPO_BRANCH}"       7 35 35 0 \
#    "BITCOIN_ELECTRS_REPO_NAME"         8 1 "${BITCOIN_ELECTRS_REPO_NAME}"         8 35 35 0 \
#    "BITCOIN_ELECTRS_REPO_URL"          9 1 "${BITCOIN_ELECTRS_REPO_URL}"          9 35 35 0 \
#    "BITCOIN_LATEST_RELEASE"            10 1 "${BITCOIN_LATEST_RELEASE}"            10 35 35 0 \
#    "BITCOIN_MAINNET_ENABLE"            11 1 "${BITCOIN_MAINNET_ENABLE}"            11 35 35 0 \
#    "BITCOIN_REPO_BRANCH"               12 1 "${BITCOIN_REPO_BRANCH}"               12 35 35 0 \
#    "BITCOIN_REPO_NAME"                 13 1 "${BITCOIN_REPO_NAME}"                 13 35 35 0 \
#    "BITCOIN_REPO_URL"                  14 1 "${BITCOIN_REPO_URL}"                  14 35 35 0 \
#    "BITCOIN_TESTNET_ENABLE"            15 1 "${BITCOIN_TESTNET_ENABLE}"            15 35 35 0 \
#    "ELEMENTS_INSTALL"                  16 1 "${ELEMENTS_INSTALL}"                  16 35 35 0 \
#    "ELEMENTS_LATEST_RELEASE"           17 1 "${ELEMENTS_LATEST_RELEASE}"           17 35 35 0 \
#    "ELEMENTS_LIQUID_ENABLE"            18 1 "${ELEMENTS_LIQUID_ENABLE}"            18 35 35 0 \
#    "ELEMENTS_REPO_BRANCH"              19 1 "${ELEMENTS_REPO_BRANCH}"              19 35 35 0 \
#    "ELEMENTS_REPO_NAME"                20 1 "${ELEMENTS_REPO_NAME}"                20 35 35 0 \
#    "ELEMENTS_REPO_URL"                 21 1 "${ELEMENTS_REPO_URL}"                 21 35 35 0 \
#    "MEMPOOL_LATEST_RELEASE"            22 1 "${MEMPOOL_LATEST_RELEASE}"            22 35 35 0 \
#    "MEMPOOL_LIQUID_HTTP_HOST"          23 1 "${MEMPOOL_LIQUID_HTTP_HOST}"          23 35 35 0 \
#    "MEMPOOL_LIQUID_HTTP_PORT"          24 1 "${MEMPOOL_LIQUID_HTTP_PORT}"          24 35 35 0 \
#    "MEMPOOL_MAINNET_HTTP_HOST"         25 1 "${MEMPOOL_MAINNET_HTTP_HOST}"         25 35 35 0 \
#    "MEMPOOL_MAINNET_HTTP_PORT"         26 1 "${MEMPOOL_MAINNET_HTTP_PORT}"         26 35 35 0 \
#    "MEMPOOL_REPO_BRANCH"               27 1 "${MEMPOOL_REPO_BRANCH}"               27 35 35 0 \
#    "MEMPOOL_REPO_NAME"                 28 1 "${MEMPOOL_REPO_NAME}"                 28 35 35 0 \
#    "MEMPOOL_REPO_URL"                  29 1 "${MEMPOOL_REPO_URL}"                  29 35 35 0 \
#    "MEMPOOL_TESTNET_HTTP_HOST"         30 1 "${MEMPOOL_TESTNET_HTTP_HOST}"         30 35 35 0 \
#    "MEMPOOL_TESTNET_HTTP_PORT"         31 1 "${MEMPOOL_TESTNET_HTTP_PORT}"         31 35 35 0 \
#    "MEMPOOL_TOR_HS"                    32 1 "${MEMPOOL_TOR_HS}"                    32 35 35 0 \
#    "HOSTNAME"                          33 1 "${HOSTNAME}"                          33 35 35 0 \
#    "TOR_INSTALL"                       34 1 "${TOR_INSTALL}"                       34 35 35 0 \
#    "CERTBOT_INSTALL"                   35 1 "${CERTBOT_INSTALL}"                   35 35 35 0 \
#2> $tempfile
#
#retval=$?
#
#if [ $retval != $DIALOG_OK ];then
#    echo "Installation aborted."
#    exit 1
#fi

############################
# START DOING ACTUAL STUFF #
############################

date
echo "[*] Mempool installation script for ${OS}"

###################################
# create filesystems if necessary #
###################################

case $OS in
    FreeBSD)
        zfsCreateFilesystems
    ;;
    Debian)
        ext4CreateDir
    ;;
esac

###############################
# Install all the OS packages #
###############################

osPackageUpdate
osPackageUpgrade
osPackageInstallAll

##########################
# Mempool top-level repo #
##########################

echo "[*] Creating Mempool user with Tor access"
osGroupCreate "${MEMPOOL_GROUP}"
osUserCreate "${MEMPOOL_USER}" "${MEMPOOL_HOME}" "${MEMPOOL_GROUP}"
osSudo "${ROOT_USER}" chsh -s `which zsh` "${MEMPOOL_USER}"
id "${MEMPOOL_USER}"

echo "[*] Creating Mempool data folder"
osSudo "${ROOT_USER}" mkdir -p "${MEMPOOL_HOME}"
osSudo "${ROOT_USER}" chown -R "${MEMPOOL_USER}:${MEMPOOL_GROUP}" "${MEMPOOL_HOME}"
osSudo "${ROOT_USER}" chown -R "${MEMPOOL_USER}:${MEMPOOL_GROUP}" /backup
osSudo "${MEMPOOL_USER}" touch "${MEMPOOL_HOME}/.zshrc"

echo "[*] Cloning Mempool repo from ${MEMPOOL_REPO_URL}"
osSudo "${MEMPOOL_USER}" git config --global pull.rebase true
osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}"
osSudo "${MEMPOOL_USER}" ln -s mempool/production/mempool-build-all upgrade
osSudo "${MEMPOOL_USER}" ln -s mempool/production/mempool-kill-all stop
osSudo "${MEMPOOL_USER}" ln -s mempool/production/mempool-start-all start
osSudo "${MEMPOOL_USER}" ln -s mempool/production/mempool-reset-all reset


case $OS in
    FreeBSD)
        echo "[*] Installing syslog configuration"
        osSudo "${ROOT_USER}" mkdir -p /usr/local/etc/syslog.d
        osSudo "${ROOT_USER}" install -c -m 755 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/mempool-logger" /usr/local/bin/mempool-logger
        osSudo "${ROOT_USER}" install -c -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/syslog.conf" /usr/local/etc/syslog.d/mempool.conf

        echo "[*] Installing newsyslog configuration"
        osSudo "${ROOT_USER}" mkdir -p /usr/local/etc/newsyslog.conf.d
        osSudo "${ROOT_USER}" install -c -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/newsyslog-mempool-backend.conf" /usr/local/etc/newsyslog.conf.d/newsyslog-mempool-backend.conf
        osSudo "${ROOT_USER}" install -c -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/newsyslog-mempool-nginx.conf" /usr/local/etc/newsyslog.conf.d/newsyslog-mempool-nginx.conf

        echo "[*] Creating log files"
        osSudo "${ROOT_USER}" newsyslog -C
    ;;
    Debian)
        echo "[*] Installing syslog configuration"
        osSudo "${ROOT_USER}" install -c -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/rsyslog.conf" /etc/rsyslog.d/10-mempool.conf
        osSudo "${ROOT_USER}" sed -i.orig -e 's/^\*\.\*;auth,authpriv\.none/*\.*;auth,authpriv\.none,local7\.none/' /etc/rsyslog.d/50-default.conf
    ;;
esac

echo "[*] Installing Mempool crontab"
osSudo "${ROOT_USER}" crontab -u "${MEMPOOL_USER}" "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/mempool.crontab"

echo "[*] Installing nvm.sh from GitHub"
osSudo "${MEMPOOL_USER}" sh -c 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | zsh'

echo "[*] Building NodeJS v20.4.0 via nvm.sh"
osSudo "${MEMPOOL_USER}" zsh -c 'source ~/.zshrc ; nvm install v20.4.0 --shared-zlib'
echo "[*] Building NodeJS v18.16.1 via nvm.sh"
osSudo "${MEMPOOL_USER}" zsh -c 'source ~/.zshrc ; nvm install v18.16.1 --shared-zlib'
osSudo "${MEMPOOL_USER}" zsh -c 'source ~/.zshrc ; nvm alias default 18.16.1'

####################
# Tor installation #
####################

if [ "${TOR_INSTALL}" = ON ];then

    echo "[*] Installing Tor package"
    osPackageInstall "${TOR_PKG}"

    echo "[*] Installing Tor base configuration"
    osSudo "${ROOT_USER}" install -c -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/torrc" "${TOR_CONFIGURATION}"
    osSudo "${ROOT_USER}" sed -i.orig "s!__TOR_RESOURCES__!${TOR_RESOURCES}!" "${TOR_CONFIGURATION}"

    echo "[*] Adding Tor HS configuration for Bisq"
    if [ "${BISQ_MAINNET_ENABLE}" = "ON" ];then
        if ! grep "${BISQ_TOR_HS}" "${TOR_CONFIGURATION}" >/dev/null 2>&1;then
            osSudo "${ROOT_USER}" /bin/sh -c "echo HiddenServiceDir ${TOR_RESOURCES}/${BISQ_TOR_HS}/ >> ${TOR_CONFIGURATION}"
            osSudo "${ROOT_USER}" /bin/sh -c "echo HiddenServicePort 80 127.0.0.1:82 >> ${TOR_CONFIGURATION}"
            osSudo "${ROOT_USER}" /bin/sh -c "echo HiddenServiceVersion 3 >> ${TOR_CONFIGURATION}"
        fi
    fi

    echo "[*] Adding Tor HS configuration for Liquid"
    if [ "${ELEMENTS_LIQUID_ENABLE}" = "ON" ];then
        if ! grep "${LIQUID_TOR_HS}" "${TOR_CONFIGURATION}" >/dev/null 2>&1;then
            osSudo "${ROOT_USER}" /bin/sh -c "echo HiddenServiceDir ${TOR_RESOURCES}/${LIQUID_TOR_HS}/ >> ${TOR_CONFIGURATION}"
            osSudo "${ROOT_USER}" /bin/sh -c "echo HiddenServicePort 80 127.0.0.1:83 >> ${TOR_CONFIGURATION}"
            osSudo "${ROOT_USER}" /bin/sh -c "echo HiddenServiceVersion 3 >> ${TOR_CONFIGURATION}"
        fi
    fi

    case $OS in
        FreeBSD)
            echo net.inet.ip.random_id=1 >> /etc/sysctl.conf
            sysctl net.inet.ip.random_id=1
        ;;
    esac

    # start tor now so it can bootstrap in time for bitcoin starting a few mins later
    echo "[*] Starting Tor service"
    osSudo "${ROOT_USER}" service tor restart
fi

########################
# Bitcoin installation #
########################

if [ "${BITCOIN_INSTALL}" = ON ];then

    echo "[*] Creating Bitcoin user with Tor access"
    osGroupCreate "${BITCOIN_GROUP}"
    if [ "${TOR_INSTALL}" = ON ];then
        osUserCreate "${BITCOIN_USER}" "${BITCOIN_HOME}" "${BITCOIN_GROUP}" "${TOR_GROUP}"
    else
        osUserCreate "${BITCOIN_USER}" "${BITCOIN_HOME}" "${BITCOIN_GROUP}"
    fi
    osSudo "${ROOT_USER}" chsh -s `which zsh` "${BITCOIN_USER}"

    echo "[*] Creating Bitcoin minfee user with Tor access"
    osGroupCreate "${MINFEE_GROUP}"
    if [ "${TOR_INSTALL}" = ON ];then
        osUserCreate "${MINFEE_USER}" "${MINFEE_HOME}" "${MINFEE_GROUP}" "${TOR_GROUP}"
    else
        osUserCreate "${MINFEE_USER}" "${MINFEE_HOME}" "${MINFEE_GROUP}"
    fi
    osSudo "${ROOT_USER}" chown -R "${MINFEE_USER}:${MINFEE_GROUP}" "${MINFEE_HOME}"
    osSudo "${ROOT_USER}" chsh -s `which zsh` "${MINFEE_USER}"
    osSudo "${MINFEE_USER}" touch "${MINFEE_HOME}/.zshrc"
    osSudo "${MINFEE_USER}" ln -s . .bitcoin

    echo "[*] Creating Bitcoin data folder"
    osSudo "${ROOT_USER}" mkdir -p "${BITCOIN_HOME}"
    osSudo "${ROOT_USER}" chown -R "${BITCOIN_USER}:${BITCOIN_GROUP}" "${BITCOIN_HOME}"
    osSudo "${BITCOIN_USER}" touch "${BITCOIN_HOME}/.zshrc"
    osSudo "${BITCOIN_USER}" ln -s . .bitcoin

    echo "[*] Cloning Bitcoin repo from ${BITCOIN_REPO_URL}"
    osSudo "${BITCOIN_USER}" git config --global advice.detachedHead false
    osSudo "${BITCOIN_USER}" git clone --branch "${BITCOIN_REPO_BRANCH}" "${BITCOIN_REPO_URL}" "${BITCOIN_HOME}/${BITCOIN_REPO_NAME}"

    echo "[*] Checking out Bitcoin ${BITCOIN_LATEST_RELEASE}"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_HOME}/${BITCOIN_REPO_NAME} && git checkout ${BITCOIN_LATEST_RELEASE}"

    echo "[*] Building Bitcoin from source repo"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_REPO_NAME} && ./autogen.sh --quiet"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_REPO_NAME} && MAKE=gmake CC=cc CXX=c++ CPPFLAGS=-I/usr/local/include ./configure --with-gui=no --disable-wallet --disable-tests"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_REPO_NAME} && gmake -j${NPROC}"

    echo "[*] Installing Bitcoin binaries into OS"
    osSudo "${ROOT_USER}" sh -c "cd ${BITCOIN_HOME}/${BITCOIN_REPO_NAME} && gmake install"

    echo "[*] Installing Bitcoin configuration"
    osSudo "${ROOT_USER}" install -c -o "${BITCOIN_USER}" -g "${BITCOIN_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/bitcoin.conf" "${BITCOIN_HOME}/bitcoin.conf"

    echo "[*] Installing Bitcoin minfee configuration"
    osSudo "${ROOT_USER}" install -c -o "${MINFEE_USER}" -g "${MINFEE_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/bitcoin.minfee.conf" "${MINFEE_HOME}/bitcoin.conf"

    echo "[*] Installing Bitcoin RPC credentials"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_USER__/${BITCOIN_RPC_USER}/" "${BITCOIN_HOME}/bitcoin.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_PASS__/${BITCOIN_RPC_PASS}/" "${BITCOIN_HOME}/bitcoin.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_USER__/${BITCOIN_RPC_USER}/" "${MINFEE_HOME}/bitcoin.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_PASS__/${BITCOIN_RPC_PASS}/" "${MINFEE_HOME}/bitcoin.conf"
fi

#########################
# Elements installation #
#########################

if [ "${ELEMENTS_INSTALL}" = ON ];then

    echo "[*] Creating Elements user with Tor access"
    osGroupCreate "${ELEMENTS_GROUP}"
    if [ "${TOR_INSTALL}" = ON ];then
        osUserCreate "${ELEMENTS_USER}" "${ELEMENTS_HOME}" "${ELEMENTS_GROUP}" "${TOR_GROUP}"
    else
        osUserCreate "${ELEMENTS_USER}" "${ELEMENTS_HOME}" "${ELEMENTS_GROUP}"
    fi
    osSudo "${ROOT_USER}" chsh -s `which zsh` "${ELEMENTS_USER}"

    echo "[*] Creating Elements data folder"
    osSudo "${ROOT_USER}" mkdir -p "${ELEMENTS_HOME}"
    osSudo "${ROOT_USER}" chown -R "${ELEMENTS_USER}:${ELEMENTS_GROUP}" "${ELEMENTS_HOME}"
    osSudo "${ELEMENTS_USER}" touch "${ELEMENTS_HOME}/.zshrc"
    osSudo "${ELEMENTS_USER}" ln -s . .elements

    echo "[*] Cloning Elements repo from ${ELEMENTS_REPO_URL}"
    osSudo "${ELEMENTS_USER}" git config --global advice.detachedHead false
    osSudo "${ELEMENTS_USER}" git clone --branch "${ELEMENTS_REPO_BRANCH}" "${ELEMENTS_REPO_URL}" "${ELEMENTS_HOME}/${ELEMENTS_REPO_NAME}"

    echo "[*] Checking out Elements ${ELEMENTS_LATEST_RELEASE}"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_HOME}/${ELEMENTS_REPO_NAME} && git checkout ${ELEMENTS_LATEST_RELEASE}"

    echo "[*] Building Elements from source repo"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_REPO_NAME} && ./autogen.sh --quiet"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_REPO_NAME} && MAKE=gmake CC=cc CXX=c++ CPPFLAGS=-I/usr/local/include ./configure --with-gui=no --disable-wallet --disable-tests"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_REPO_NAME} && gmake -j${NPROC}"

    echo "[*] Installing Elements binaries into OS"
    osSudo "${ROOT_USER}" sh -c "cd ${ELEMENTS_HOME}/${ELEMENTS_REPO_NAME} && gmake install"

    echo "[*] Installing Elements configuration"
    osSudo "${ROOT_USER}" install -c -o "${ELEMENTS_USER}" -g "${ELEMENTS_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/elements.conf" "${ELEMENTS_HOME}/elements.conf"

    echo "[*] Configuring Elements Liquid RPC credentials in elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_USER__/${BITCOIN_RPC_USER}/" "${ELEMENTS_HOME}/elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_PASS__/${BITCOIN_RPC_PASS}/" "${ELEMENTS_HOME}/elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__ELEMENTS_RPC_USER__/${ELEMENTS_RPC_USER}/" "${ELEMENTS_HOME}/elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__ELEMENTS_RPC_PASS__/${ELEMENTS_RPC_PASS}/" "${ELEMENTS_HOME}/elements.conf"
fi

###################################
# Bitcoin -> Electrs installation #
###################################

if [ "${BITCOIN_ELECTRS_INSTALL}" = ON ];then

    echo "[*] Creating Bitcoin Electrs data folder"
    osSudo "${ROOT_USER}" mkdir -p "${BITCOIN_ELECTRS_HOME}"
    osSudo "${ROOT_USER}" chown -R "${BITCOIN_USER}:${BITCOIN_GROUP}" "${BITCOIN_ELECTRS_HOME}"
    if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
        osSudo "${ROOT_USER}" chown -R "${BITCOIN_USER}:${BITCOIN_GROUP}" "${ELECTRS_MAINNET_DATA}"
    fi
    if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
        osSudo "${ROOT_USER}" chown -R "${BITCOIN_USER}:${BITCOIN_GROUP}" "${ELECTRS_TESTNET_DATA}"
    fi
    if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
        osSudo "${ROOT_USER}" chown -R "${BITCOIN_USER}:${BITCOIN_GROUP}" "${ELECTRS_SIGNET_DATA}"
    fi

    echo "[*] Cloning Bitcoin Electrs repo from ${BITCOIN_ELECTRS_REPO_URL}"
    osSudo "${BITCOIN_USER}" git config --global advice.detachedHead false
    osSudo "${BITCOIN_USER}" git clone --branch "${BITCOIN_ELECTRS_REPO_BRANCH}" "${BITCOIN_ELECTRS_REPO_URL}" "${BITCOIN_HOME}/${BITCOIN_ELECTRS_REPO_NAME}"

    echo "[*] Checking out Electrs ${BITCOIN_ELECTRS_LATEST_RELEASE}"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_HOME}/${BITCOIN_ELECTRS_REPO_NAME} && git checkout ${BITCOIN_ELECTRS_LATEST_RELEASE}"

    case $OS in
        FreeBSD)
           echo "[*] Installing Rust from pkg install"
        ;;
        Debian)
           echo "[*] Installing Rust from rustup.rs"
           osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_ELECTRS_HOME} && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y"
        ;;
    esac

    echo "[*] Building Bitcoin Electrs release binary"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_ELECTRS_HOME} && cargo run --release --bin electrs -- --version" || true

    case $OS in
        FreeBSD)
            echo "[*] Patching Bitcoin Electrs code for FreeBSD"
            osSudo "${BITCOIN_USER}" sh -c "cd \"${BITCOIN_HOME}/.cargo/registry/src/index.crates.io-6f17d22bba15001f/sysconf-0.3.4\" && patch -p1 < \"${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/freebsd/sysconf.patch\""
            #osSudo "${BITCOIN_USER}" sh -c "cd \"${BITCOIN_ELECTRS_HOME}/src/new_index/\" && sed -i.bak -e s/Snappy/None/ db.rs && rm db.rs.bak"
            #osSudo "${BITCOIN_USER}" sh -c "cd \"${BITCOIN_ELECTRS_HOME}/src/bin/\" && sed -i.bak -e 's/from_secs(5)/from_secs(1)/' electrs.rs && rm electrs.rs.bak"
        ;;
        Debian)
        ;;
    esac

    echo "[*] Building Bitcoin Electrs release binary"
    osSudo "${BITCOIN_USER}" sh -c "cd ${BITCOIN_ELECTRS_HOME} && cargo run --release --bin electrs -- --version"
fi

##################################
# Liquid -> Electrs installation #
##################################

if [ "${ELEMENTS_ELECTRS_INSTALL}" = ON ];then

    echo "[*] Creating Liquid Electrs data folder"
    osSudo "${ROOT_USER}" mkdir -p "${ELEMENTS_ELECTRS_HOME}"
    osSudo "${ROOT_USER}" chown -R "${ELEMENTS_USER}:${ELEMENTS_GROUP}" "${ELEMENTS_HOME}"
    osSudo "${ROOT_USER}" chown -R "${ELEMENTS_USER}:${ELEMENTS_GROUP}" "${ELEMENTS_ELECTRS_HOME}"
    if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
        osSudo "${ROOT_USER}" chown -R "${ELEMENTS_USER}:${ELEMENTS_GROUP}" "${ELECTRS_LIQUID_DATA}"
    fi
    if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
        osSudo "${ROOT_USER}" chown -R "${ELEMENTS_USER}:${ELEMENTS_GROUP}" "${ELECTRS_LIQUIDTESTNET_DATA}"
    fi

    echo "[*] Cloning Liquid Electrs repo from ${ELEMENTS_ELECTRS_REPO_URL}"
    osSudo "${ELEMENTS_USER}" git config --global advice.detachedHead false
    osSudo "${ELEMENTS_USER}" git clone --branch "${ELEMENTS_ELECTRS_REPO_BRANCH}" "${ELEMENTS_ELECTRS_REPO_URL}" "${ELEMENTS_HOME}/${ELEMENTS_ELECTRS_REPO_NAME}"

    echo "[*] Checking out Liquid Electrs ${ELEMENTS_ELECTRS_LATEST_RELEASE}"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_HOME}/${ELEMENTS_ELECTRS_REPO_NAME} && git checkout ${ELEMENTS_ELECTRS_LATEST_RELEASE}"

    echo "[*] Cloning Liquid Asset Registry repo from ${LIQUID_ASSET_REGISTRY_DB_URL}"
    osSudo "${ELEMENTS_USER}" git config --global advice.detachedHead false
    osSudo "${ELEMENTS_USER}" git clone "${LIQUID_ASSET_REGISTRY_DB_URL}" "${ELEMENTS_HOME}/${LIQUID_ASSET_REGISTRY_DB_NAME}"

    echo "[*] Cloning Liquid Asset Registry testnet repo from ${LIQUIDTESTNET_ASSET_REGISTRY_DB_URL}"
    osSudo "${ELEMENTS_USER}" git config --global advice.detachedHead false
    osSudo "${ELEMENTS_USER}" git clone "${LIQUIDTESTNET_ASSET_REGISTRY_DB_URL}" "${ELEMENTS_HOME}/${LIQUIDTESTNET_ASSET_REGISTRY_DB_NAME}"

    echo "[*] Building Liquid Electrs release binary"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_ELECTRS_HOME} && cargo run --release --features liquid --bin electrs -- --network liquid --version" || true

    case $OS in
        FreeBSD)
            echo "[*] Patching Liquid Electrs code for FreeBSD"
            osSudo "${ELEMENTS_USER}" sh -c "cd \"${ELEMENTS_HOME}/.cargo/registry/src/index.crates.io-6f17d22bba15001f/sysconf-0.3.4\" && patch -p1 < \"${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/freebsd/sysconf.patch\""
        ;;
        Debian)
        ;;
    esac

    echo "[*] Building Liquid Electrs release binary"
    osSudo "${ELEMENTS_USER}" sh -c "cd ${ELEMENTS_ELECTRS_HOME} && cargo run --release --features liquid --bin electrs -- --network liquid --version" || true
fi

##############################
# Core Lightning for Bitcoin #
##############################

echo "[*] Installing Core Lightning"
case $OS in
    FreeBSD)
        echo "[*] Creating Core Lightning user"
        osGroupCreate "${CLN_GROUP}"
        osUserCreate "${CLN_USER}" "${CLN_HOME}" "${CLN_GROUP}"
        osSudo "${ROOT_USER}" pw usermod ${MEMPOOL_USER} -G "${CLN_GROUP}"
        osSudo "${ROOT_USER}" chsh -s `which zsh` "${CLN_USER}"
        echo "export PATH=$PATH:$HOME/.local/bin" >> "${CLN_HOME}/.zshrc"
        osSudo "${ROOT_USER}" mkdir -p "${CLN_HOME}/.lightning/bitcoin"
        osSudo "${ROOT_USER}" mkdir -p "${CLN_HOME}/.lightning/signet"
        osSudo "${ROOT_USER}" mkdir -p "${CLN_HOME}/.lightning/testnet"
        osSudo "${ROOT_USER}" chmod 750 "${CLN_HOME}" "${CLN_HOME}/.lightning"
        osSudo "${ROOT_USER}" chmod 750 "${CLN_HOME}" "${CLN_HOME}/.lightning/bitcoin"
        osSudo "${ROOT_USER}" chmod 750 "${CLN_HOME}" "${CLN_HOME}/.lightning/signet"
        osSudo "${ROOT_USER}" chmod 750 "${CLN_HOME}" "${CLN_HOME}/.lightning/testnet"
        osSudo "${ROOT_USER}" chown -R "${CLN_USER}:${CLN_GROUP}" "${CLN_HOME}"
        echo "[*] Creating symlink to .bitcoin folder"
        osSudo "${CLN_USER}" ln -s "${BITCOIN_HOME}/.bitcoin" "${CLN_HOME}/.bitcoin"

        echo "[*] Installing Core Lightning package"
        osPackageInstall ${CLN_PKG}

######## FIXME: this code doesn't work properly, needs fixing
#
#        echo "[*] Installing Core Lightning mainnet Cronjob"
#        public_ipv4=$( ifconfig | grep 'inet ' | awk -F ' ' '{ print $2 }' | grep -v '^103\.165\.192\.' | grep -v '^127\.0\.0\.1' )
#        public_ipv6=$( ifconfig | grep 'inet6' | awk -F ' ' '{ print $2 }' | grep -v '^2001:df6:7280::' | grep -v '^fe80::' | grep -v '^::1' )
#
#        crontab_cln+="@reboot sleep 10 ; screen -dmS main lightningd --rpc-file-mode 0660 --alias `hostname` --disable-ip-discovery --autolisten false --bind-addr $public_ipv4 --announce-addr $public_ipv4 --bind-addr $public_ipv6 --announce-addr $public_ipv6\n"
#        crontab_cln+="@reboot sleep 10 ; screen -dmS tes lightningd --rpc-file-mode 0660 --alias `hostname` --network testnet --disable-ip-discovery --autolisten false --bind-addr $public_ipv4 --announce-addr $public_ipv4 --bind-addr $public_ipv6 --announce-addr $public_ipv6\n"
#        crontab_cln+="@reboot sleep 10 ; screen -dmS sig lightningd --rpc-file-mode 0660 --alias `hostname` --network signet --disable-ip-discovery --autolisten false --bind-addr $public_ipv4 --announce-addr $public_ipv4 --bind-addr $public_ipv6 --announce-addr $public_ipv6 \n"
#        crontab_cln+="@reboot sleep 20 ; /mempool/mempool.space/lightning-seeder >/dev/null 2>&1\n"
#        crontab_cln+="1 * * * * /mempool/mempool.space/lightning-seeder >/dev/null 2>&1\n"
#        echo "${crontab_cln}" | crontab -u "${CLN_USER}" -
    ;;
    Debian)
    ;;
esac


#####################
# Bisq installation #
#####################

if [ "${BISQ_INSTALL}" = ON ];then

    echo "[*] Creating Bisq user with Tor access"
    osGroupCreate "${BISQ_GROUP}"
    if [ "${TOR_INSTALL}" = ON ];then
        osUserCreate "${BISQ_USER}" "${BISQ_HOME}" "${BISQ_GROUP}" "${TOR_GROUP}"
    else
        osUserCreate "${BISQ_USER}" "${BISQ_HOME}" "${BISQ_GROUP}"
    fi
    osSudo "${ROOT_USER}" chsh -s `which zsh` "${BISQ_USER}"

    echo "[*] Creating Bisq data folder"
    osSudo "${ROOT_USER}" mkdir -p "${BISQ_HOME}"
    osSudo "${ROOT_USER}" chown -R "${BISQ_USER}:${BISQ_GROUP}" "${BISQ_HOME}"
    osSudo "${BISQ_USER}" touch "${BISQ_HOME}/.zshrc"

    echo "[*] Building Bisq"
    case $OS in

        FreeBSD)
            echo "[*] FIXME: Bisq must be installed manually on FreeBSD"
        ;;

        Debian)
            echo "[*] Cloning Bisq top-level repo"
            osSudo "${BISQ_USER}" git clone --branch "${BISQ_REPO_BRANCH}" "${BISQ_REPO_URL}" "${BISQ_HOME}/${BISQ_REPO_NAME}"

            echo "[*] Installing OpenJDK from Bisq install_java_linux.sh script"
            osSudo "${ROOT_USER}" "${BISQ_HOME}/${BISQ_REPO_NAME}/scripts/install_java_linux.sh"

            echo "[*] Checking out Bisq ${BISQ_LATEST_RELEASE}"
            osSudo "${BISQ_USER}" sh -c "cd ${BISQ_HOME}/${BISQ_REPO_NAME} && git checkout ${BISQ_LATEST_RELEASE}"

            echo "[*] Performing Git LFS pull"
            osSudo "${BISQ_USER}" sh -c "cd ${BISQ_HOME}/${BISQ_REPO_NAME} && git lfs pull"

            echo "[*] Building Bisq from source"
            osSudo "${BISQ_USER}" sh -c "cd ${BISQ_HOME}/${BISQ_REPO_NAME} && ./gradlew build -x test < /dev/null" # redirect from /dev/null is necessary to workaround gradlew non-interactive shell hanging issue

        ;;
    esac

    echo "[*] Configuring Bisq"
    case $OS in

        FreeBSD)
            echo "[*] FIXME: Bisq must be configured manually on FreeBSD"
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${BISQ_HOME}/${BISQ_REPO_NAME}/seednode/bisq.service" "${DEBIAN_SERVICE_HOME}/bisq.service"
            osSudo "${ROOT_USER}" sed -i.orig "s/#Requires=bitcoin.service/Requires=bitcoin.service/" "${DEBIAN_SERVICE_HOME}/bisq.service"
            osSudo "${ROOT_USER}" sed -i.orig "s/#BindsTo=bitcoin.service/BindsTo=bitcoin.service/" "${DEBIAN_SERVICE_HOME}/bisq.service"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BISQ_REPO_NAME__/${BISQ_REPO_NAME}/" "${DEBIAN_SERVICE_HOME}/bisq.service"
            osSudo "${ROOT_USER}" sed -i.orig "s!__BISQ_HOME__!${BISQ_HOME}!" "${DEBIAN_SERVICE_HOME}/bisq.service"

            echo "[*] Installing Bisq environment file"
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${BISQ_HOME}/${BISQ_REPO_NAME}/seednode/bisq.env" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s!__BISQ_APP_NAME__!${BISQ_APP_NAME}!" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s!__BISQ_HOME__!${BISQ_HOME}!" "${DEBIAN_ENV_HOME}/bisq.env"

            echo "[*] Configuring Bisq environment file with Bitcoin RPC credentials"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_P2P_HOST__/${BITCOIN_MAINNET_P2P_HOST}/" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_P2P_PORT__/${BITCOIN_MAINNET_P2P_PORT}/" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_HOST__/${BITCOIN_MAINNET_RPC_HOST}/" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_PORT__/${BITCOIN_MAINNET_RPC_PORT}/" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_USER__/${BITCOIN_RPC_USER}/" "${DEBIAN_ENV_HOME}/bisq.env"
            osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_PASS__/${BITCOIN_RPC_PASS}/" "${DEBIAN_ENV_HOME}/bisq.env"

            #echo "[*] Updating Bitcoin configuration for Bisq"
            #osSudo "${ROOT_USER}" sed -i.orig "s/#blocknotify/blocknotify/" "${BITCOIN_HOME}/bitcoin.conf"
            #osSudo "${BITCOIN_USER}" install -c -o "${BITCOIN_USER}" -g "${BITCOIN_GROUP}" -m 755 "${BISQ_HOME}/${BISQ_REPO_NAME}/seednode/blocknotify.sh" "${BITCOIN_HOME}/blocknotify.sh"
        ;;

    esac
fi

#######################
# Unfurl installation #
#######################

if [ "${UNFURL_INSTALL}" = ON ];then

    echo "[*] Insalling Unfurl source"
    case $OS in

        FreeBSD)

            if pciconf -lv|grep -i nvidia >/dev/null 2>&1;then
                echo "[*] GPU detected: Installing packages for Unfurl"
                osPackageInstall ${FREEBSD_UNFURL_PKG[@]}

                echo 'allowed_users = anybody' >> /usr/local/etc/X11/Xwrapper.config
                echo 'kld_list="nvidia"' >> /etc/rc.conf
                echo 'nvidia_xorg_enable="YES"' >> /etc/rc.conf

                echo "[*] Installing color emoji"
                osSudo "${ROOT_USER}" curl "https://github.com/samuelngs/apple-emoji-linux/releases/download/ios-15.4/AppleColorEmoji.ttf" -o /usr/local/share/fonts/TTF/AppleColorEmoji.ttf
                cat > /usr/local/etc/fonts/conf.d/01-emoji.conf <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<match>
<test name="family"><string>sans-serif</string></test>
<edit name="family" mode="prepend" binding="strong">
<string>Apple Color Emoji</string>
</edit>
</match>
<match>
<test name="family"><string>serif</string></test>
<edit name="family" mode="prepend" binding="strong">
<string>Apple Color Emoji</string>
</edit>
</match>
<match>
<test name="family"><string>Apple Color Emoji</string></test>
<edit name="family" mode="prepend" binding="strong">
<string>Apple Color Emoji</string>
</edit>
</match>
</fontconfig>
EOF
            fi
        ;;

        Debian)
            echo "[*] Installing packages for Unfurl"
            osPackageInstall ${DEBIAN_UNFURL_PKG[@]}
            echo "[*] Cloning Mempool (Unfurl) repo from ${UNFURL_REPO_URL}"
            osSudo "${UNFURL_USER}" git config --global pull.rebase true
            osSudo "${UNFURL_USER}" git config --global advice.detachedHead false
            osSudo "${UNFURL_USER}" git clone --branch "${UNFURL_REPO_BRANCH}" "${UNFURL_REPO_URL}" "${UNFURL_HOME}/${UNFURL_REPO_NAME}"
            osSudo "${UNFURL_USER}" ln -s unfurl/production/unfurl-build upgrade
            osSudo "${UNFURL_USER}" ln -s unfurl/production/unfurl-kill stop
            osSudo "${UNFURL_USER}" ln -s unfurl/production/unfurl-start start
            echo "[*] Installing nvm.sh from GitHub"
            osSudo "${UNFURL_USER}" sh -c 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | zsh'

            echo "[*] Building NodeJS via nvm.sh"
            osSudo "${UNFURL_USER}" zsh -c 'source ~/.zshrc ; nvm install v16.16.0 --shared-zlib'

        ;;
    esac

fi

################################
# Bitcoin instance for Mainnet #
################################

if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
    echo "[*] Installing Bitcoin Mainnet service"
    case $OS in

        FreeBSD)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 755 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/freebsd/rc.d/bitcoin" "${FREEBSD_SERVICE_HOME}"
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/bitcoin.service" "${DEBIAN_SERVICE_HOME}"
        ;;
    esac
fi

#######################################
# Bitcoin instance for Mainnet Minfee #
#######################################

if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
    echo "[*] Installing Bitcoin Minfee service"
    case $OS in

        FreeBSD)
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/bitcoin-minfee.service" "${DEBIAN_SERVICE_HOME}"
        ;;
    esac
fi

################################
# Bitcoin instance for Testnet #
################################

if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
    echo "[*] Installing Bitcoin Testnet service"
    case $OS in

        FreeBSD)
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/bitcoin-testnet.service" "${DEBIAN_SERVICE_HOME}"
        ;;
    esac
fi

###############################
# Bitcoin instance for Signet #
###############################

if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
    echo "[*] Installing Bitcoin Signet service"
    case $OS in

        FreeBSD)
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/bitcoin-signet.service" "${DEBIAN_SERVICE_HOME}"
        ;;
    esac
fi

###############################
# Bitcoin instance for Liquid #
###############################

if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
    echo "[*] Installing Bitcoin Liquid service"
    case $OS in

        FreeBSD)
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/elements-liquid.service" "${DEBIAN_SERVICE_HOME}"
        ;;
    esac
fi

#######################################
# Bitcoin instance for Liquid Testnet #
#######################################

if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
    echo "[*] Installing Bitcoin Liquid service"
    case $OS in

        FreeBSD)
        ;;

        Debian)
            osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/linux/elements-liquidtestnet.service" "${DEBIAN_SERVICE_HOME}"
        ;;
    esac
fi

########################################
# Electrs instance for Bitcoin Mainnet #
########################################
if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
    echo "[*] FIXME: must only crontab enabled daemons"
fi

########################################
# Electrs instance for Bitcoin Testnet #
########################################

if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
    echo "[*] FIXME: must only crontab enabled daemons"
fi

#######################################
# Electrs instance for Bitcoin Signet #
#######################################

if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
    echo "[*] FIXME: must only crontab enabled daemons"
fi

########################################
# Electrs instance for Elements Liquid #
########################################

if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
    echo "[*] Installing Elements crontab"
    case $OS in
        FreeBSD)
            osSudo "${ROOT_USER}" crontab -u "${ELEMENTS_USER}" "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/elements.crontab"
        ;;
    esac
fi

################################################
# Electrs instance for Elements Liquid Testnet #
################################################

if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
    echo "[*] Installing Elements Liquid Testnet electrs start script"
    osSudo "${ROOT_USER}" install -c -o "${ELEMENTS_USER}" -g "${ELEMENTS_GROUP}" -m 755 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/electrs-start-liquidtestnet" "${ELEMENTS_ELECTRS_HOME}"

    echo "[*] Installing Elements Liquid Testnet RPC credentials"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_USER__/${BITCOIN_RPC_USER}/" "${ELEMENTS_HOME}/elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__BITCOIN_RPC_PASS__/${BITCOIN_RPC_PASS}/" "${ELEMENTS_HOME}/elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__ELEMENTS_RPC_USER__/${ELEMENTS_RPC_USER}/" "${ELEMENTS_HOME}/elements.conf"
    osSudo "${ROOT_USER}" sed -i.orig "s/__ELEMENTS_RPC_PASS__/${ELEMENTS_RPC_PASS}/" "${ELEMENTS_HOME}/elements.conf"

    echo "[*] Configuring Elements LiquidTestnet RPC credentials in electrs start script"
    osSudo "${ROOT_USER}" sed -i.orig "s/__ELEMENTS_RPC_USER__/${ELEMENTS_RPC_USER}/" "${ELEMENTS_ELECTRS_HOME}/electrs-start-liquidtestnet"
    osSudo "${ROOT_USER}" sed -i.orig "s/__ELEMENTS_RPC_PASS__/${ELEMENTS_RPC_PASS}/" "${ELEMENTS_ELECTRS_HOME}/electrs-start-liquidtestnet"
    osSudo "${ROOT_USER}" sed -i.orig "s!__ELECTRS_DATA_ROOT__!${ELECTRS_DATA_ROOT}!" "${ELEMENTS_ELECTRS_HOME}/electrs-start-liquidtestnet"
fi

################################
# Install all Electrs Cronjobs #
################################
echo "[*] Installing crontabs"
case $OS in
    FreeBSD)
        osSudo "${ROOT_USER}" crontab -u "${BITCOIN_USER}" "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/bitcoin.crontab"
        osSudo "${ROOT_USER}" crontab -u "${MINFEE_USER}" "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/minfee.crontab"
    ;;
    Debian)
        crontab_bitcoin=()
        if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
            echo "[*] Installing Electrs Mainnet Cronjob"
            crontab_bitcoin+="@reboot sleep 30 ; screen -dmS mainnet /bitcoin/electrs/electrs-start-mainnet\n"
        fi
        if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
            echo "[*] Installing Electrs Testnet Cronjob"
            crontab_bitcoin+="@reboot sleep 70 ; screen -dmS testnet /bitcoin/electrs/electrs-start-testnet\n"
        fi
        if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
            echo "[*] Installing Electrs Signet Cronjob"
            crontab_bitcoin+="@reboot sleep 90 ; screen -dmS signet /bitcoin/electrs/electrs-start-signet\n"
        fi
        if [ "${BITCOIN_MAINNET_ENABLE}" = ON -o "${BITCOIN_TESTNET_ENABLE}" = ON -o "${BITCOIN_SIGNET_ENABLE}" = ON ];then
            echo "${crontab_bitcoin}" | crontab -u "${BITCOIN_USER}" -
        fi

        crontab_elements=()
        if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
            echo "[*] Installing Liquid Asset Mainnet Cronjob"
            crontab_elements+="6 * * * * cd $HOME/asset_registry_db && git pull origin master >/dev/null 2>&1\n"
        fi
        if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
            echo "[*] Installing Liquid Asset Testnet Cronjob"
            crontab_elements+="6 * * * * cd $HOME/asset_registry_testnet_db && git pull origin master >/dev/null 2>&1\n"
        fi
        if [ "${ELEMENTS_LIQUID_ENABLE}" = ON -o "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
            echo "${crontab_elements}" | crontab -u "${ELEMENTS_USER}" -
        fi
    ;;
esac

#####################################
# Bisq instance for Bitcoin Mainnet #
#####################################

if [ "${BISQ_MAINNET_ENABLE}" = ON ];then
fi

##### Mempool -> Bitcoin Mainnet instance

if [ "${BITCOIN_MAINNET_ENABLE}" = ON -o "${BITCOIN_TESTNET_ENABLE}" = ON -o "${BITCOIN_SIGNET_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Bitcoin Mainnet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/mainnet"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Bitcoin Mainnet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/mainnet && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${BITCOIN_MAINNET_LIGHTNING_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Lightning Network on Bitcoin Mainnet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/mainnet-lightning"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Lightning Network on Bitcoin Mainnet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/mainnet-lightning && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Bitcoin Testnet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/testnet"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Bitcoin Testnet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/testnet && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${BITCOIN_TESTNET_LIGHTNING_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Lightning Network on Bitcoin Testnet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/testnet-lightning"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Lightning Network on Bitcoin Testnet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/testnet-lightning && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Bitcoin Signet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/signet"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Bitcoin Signet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/signet && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${BITCOIN_SIGNET_LIGHTNING_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Lightning Network on Bitcoin Signet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/signet-lightning"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Lightning Network on Bitcoin Signet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/signet-lightning && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Liquid"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/liquid"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Liquid"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/liquid && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
    echo "[*] Creating Mempool instance for Liquid Testnet"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/liquidtestnet"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Liquid Testnet"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/liquidtestnet && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

if [ "${BISQ_INSTALL}" = ON ];then
    echo "[*] Creating Mempool instance for Bisq"
    osSudo "${MEMPOOL_USER}" git config --global advice.detachedHead false
    osSudo "${MEMPOOL_USER}" git clone --branch "${MEMPOOL_REPO_BRANCH}" "${MEMPOOL_REPO_URL}" "${MEMPOOL_HOME}/bisq"

    echo "[*] Checking out Mempool ${MEMPOOL_LATEST_RELEASE} for Bisq"
    osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME}/bisq && git checkout ${MEMPOOL_LATEST_RELEASE}"
fi

##### mariadb

echo "[*] Adding MySQL configuration"
case $OS in

    FreeBSD)
        osSudo "${ROOT_USER}" service mysql-server onestart
    ;;
    Debian)
        osSudo "${ROOT_USER}" service mysql start
    ;;
esac

# wait for mysql to start
sleep 5

mysql << _EOF_
create database mempool;
grant all on mempool.* to '${MEMPOOL_MAINNET_USER}'@'localhost' identified by '${MEMPOOL_MAINNET_PASS}';

create database mempool_testnet;
grant all on mempool_testnet.* to '${MEMPOOL_TESTNET_USER}'@'localhost' identified by '${MEMPOOL_TESTNET_PASS}';

create database mempool_signet;
grant all on mempool_signet.* to '${MEMPOOL_SIGNET_USER}'@'localhost' identified by '${MEMPOOL_SIGNET_PASS}';

create database mempool_mainnet_lightning;
grant all on mempool_mainnet_lightning.* to '${MEMPOOL_MAINNET_LIGHTNING_USER}'@'localhost' identified by '${MEMPOOL_MAINNET_LIGHTNING_PASS}';

create database mempool_testnet_lightning;
grant all on mempool_testnet_lightning.* to '${MEMPOOL_TESTNET_LIGHTNING_USER}'@'localhost' identified by '${MEMPOOL_TESTNET_LIGHTNING_PASS}';

create database mempool_signet_lightning;
grant all on mempool_signet_lightning.* to '${MEMPOOL_SIGNET_LIGHTNING_USER}'@'localhost' identified by '${MEMPOOL_SIGNET_LIGHTNING_PASS}';

create database mempool_liquid;
grant all on mempool_liquid.* to '${MEMPOOL_LIQUID_USER}'@'localhost' identified by '${MEMPOOL_LIQUID_PASS}';

create database mempool_liquidtestnet;
grant all on mempool_liquidtestnet.* to '${MEMPOOL_LIQUIDTESTNET_USER}'@'localhost' identified by '${MEMPOOL_LIQUIDTESTNET_PASS}';

create database mempool_bisq;
grant all on mempool_bisq.* to '${MEMPOOL_BISQ_USER}'@'localhost' identified by '${MEMPOOL_BISQ_PASS}';
_EOF_

echo "[*] save MySQL credentials"
cat > "${MEMPOOL_MYSQL_CREDENTIALS}" << _EOF_
declare -x MEMPOOL_MAINNET_USER="${MEMPOOL_MAINNET_USER}"
declare -x MEMPOOL_MAINNET_PASS="${MEMPOOL_MAINNET_PASS}"
declare -x MEMPOOL_TESTNET_USER="${MEMPOOL_TESTNET_USER}"
declare -x MEMPOOL_TESTNET_PASS="${MEMPOOL_TESTNET_PASS}"
declare -x MEMPOOL_SIGNET_USER="${MEMPOOL_SIGNET_USER}"
declare -x MEMPOOL_SIGNET_PASS="${MEMPOOL_SIGNET_PASS}"
declare -x MEMPOOL_MAINNET_LIGHTNING_USER="${MEMPOOL_MAINNET_LIGHTNING_USER}"
declare -x MEMPOOL_MAINNET_LIGHTNING_PASS="${MEMPOOL_MAINNET_LIGHTNING_PASS}"
declare -x MEMPOOL_TESTNET_LIGHTNING_USER="${MEMPOOL_TESTNET_LIGHTNING_USER}"
declare -x MEMPOOL_TESTNET_LIGHTNING_PASS="${MEMPOOL_TESTNET_LIGHTNING_PASS}"
declare -x MEMPOOL_SIGNET_LIGHTNING_USER="${MEMPOOL_SIGNET_LIGHTNING_USER}"
declare -x MEMPOOL_SIGNET_LIGHTNING_PASS="${MEMPOOL_SIGNET_LIGHTNING_PASS}"
declare -x MEMPOOL_LIQUID_USER="${MEMPOOL_LIQUID_USER}"
declare -x MEMPOOL_LIQUID_PASS="${MEMPOOL_LIQUID_PASS}"
declare -x MEMPOOL_LIQUIDTESTNET_USER="${MEMPOOL_LIQUIDTESTNET_USER}"
declare -x MEMPOOL_LIQUIDTESTNET_PASS="${MEMPOOL_LIQUIDTESTNET_PASS}"
declare -x MEMPOOL_BISQ_USER="${MEMPOOL_BISQ_USER}"
declare -x MEMPOOL_BISQ_PASS="${MEMPOOL_BISQ_PASS}"
_EOF_
chown "${MEMPOOL_USER}:${MEMPOOL_GROUP}" "${MEMPOOL_MYSQL_CREDENTIALS}"

##### nginx

echo "[*] Adding Nginx configuration"
osSudo "${ROOT_USER}" install -c -o "${ROOT_USER}" -g "${ROOT_GROUP}" -m 644 "${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/nginx/nginx.conf" "${NGINX_CONFIGURATION}"
mkdir -p /var/cache/nginx/services /var/cache/nginx/api
chown "${NGINX_USER}:${NGINX_GROUP}" /var/cache/nginx/services /var/cache/nginx/api
ln -s "${MEMPOOL_HOME}/mempool" "${NGINX_ETC_FOLDER}/mempool"
osSudo "${ROOT_USER}" sed -i.orig "s!__NGINX_USER__!${NGINX_USER}!" "${NGINX_CONFIGURATION}"
osSudo "${ROOT_USER}" sed -i.orig "s!__NGINX_ETC_FOLDER__!${NGINX_ETC_FOLDER}!" "${NGINX_CONFIGURATION}"

if [ "${TOR_INSTALL}" = ON ];then
    echo "[*] Read tor v3 onion hostnames"

    NGINX_MEMPOOL_ONION=$(cat "${TOR_RESOURCES}/mempool/hostname")
    osSudo "${ROOT_USER}" sed -i.orig "s!__NGINX_MEMPOOL_ONION__!${NGINX_MEMPOOL_ONION%.onion}!" "${NGINX_CONFIGURATION}"

    if [ "${ELEMENTS_LIQUID_ENABLE}" = "ON" ];then
        NGINX_LIQUID_ONION=$(cat "${TOR_RESOURCES}/liquid/hostname")
        osSudo "${ROOT_USER}" sed -i.orig "s!__NGINX_LIQUID_ONION__!${NGINX_LIQUID_ONIONi%.onion}!" "${NGINX_CONFIGURATION}"
    fi

    if [ "${BISQ_MAINNET_ENABLE}" = "ON" ];then
        NGINX_BISQ_ONION=$(cat "${TOR_RESOURCES}/bisq/hostname")
        osSudo "${ROOT_USER}" sed -i.orig "s!__NGINX_BISQ_ONION__!${NGINX_BISQ_ONION%.onion}!" "${NGINX_CONFIGURATION}"
    fi
fi

##### OS systemd

echo "[*] Setting permissions for electrs sockets"
case $OS in

    FreeBSD)
        setfacl -m "user:bitcoin:full_set:f:allow,user:mempool:full_set:f:allow,user:www:full_set:f:allow,everyone@::f:allow" "${BITCOIN_HOME}/socket"
        chown "${BITCOIN_USER}:${BITCOIN_GROUP}" "${BITCOIN_HOME}/socket"
        setfacl -m "user:elements:full_set:f:allow,user:mempool:full_set:f:allow,user:www:full_set:f:allow,everyone@::f:allow" "${ELEMENTS_HOME}/socket"
        chown "${ELEMENTS_USER}:${ELEMENTS_GROUP}" "${ELEMENTS_HOME}/socket"
    ;;

    Debian)
    ;;
esac

##### OS systemd

echo "[*] Updating system startup configuration"
case $OS in

    FreeBSD)
        echo 'nginx_enable="YES"' >> /etc/rc.conf
        echo 'bitcoin_enable="YES"' >> /etc/rc.conf
        echo 'tor_enable="YES"' >> /etc/rc.conf
        echo 'postfix_enable="YES"' >> /etc/rc.conf
        echo 'mysql_enable="YES"' >> /etc/rc.conf
        echo 'mysql_dbdir="/mysql"' >> /etc/rc.conf
        echo 'tor_enable="YES"' >> /etc/rc.conf
    ;;

    Debian)
        osSudo "${ROOT_USER}" systemctl daemon-reload
        if [ "${TOR_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable tor.service
        fi
        if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable bitcoin.service
        fi
        if [ "${BITCOIN_MAINNET_MINFEE_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable bitcoin-minfee.service
        fi
        if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable bitcoin-testnet.service
        fi
        if [ "${BITCOIN_SIGNET_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable bitcoin-signet.service
        fi
        if [ "${BISQ_MAINNET_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable bisq.service
        fi
        if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable elements-liquid.service
        fi
        if [ "${ELEMENTS_LIQUIDTESTNET_ENABLE}" = ON ];then
            osSudo "${ROOT_USER}" systemctl enable elements-liquidtestnet.service
        fi
    ;;
esac

echo "[*] Restarting Nginx"
osSudo "${ROOT_USER}" service nginx restart

##### OS set Linux user ulimits

echo "[*] Setting ulimits for users"
case $OS in

    FreeBSD)
    ;;

    Debian)
        cat >> /etc/security/limits.conf <<EOF
*        soft     nproc          200000
*        hard     nproc          200000
*        soft     nofile         200000
*        hard     nofile         200000
EOF
        echo "session required pam_limits.so" >> /etc/pam.d/common-session
    ;;
esac

##### Build Mempool

echo "[*] Build Mempool"
osSudo "${MEMPOOL_USER}" sh -c "cd ${MEMPOOL_HOME} && ./upgrade" || true



##### OS services

#if [ "${BITCOIN_MAINNET_ENABLE}" = ON ];then
#    echo "[*] Starting Bitcoin Mainnet"
#    case $OS in
#
#        FreeBSD)
#            osSudo "${ROOT_USER}" service bitcoin onestart
#            osSudo "${BITCOIN_USER}" sh -c "grep @reboot ${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/bitcoin.crontab|cut -d ';' -f2|zsh"
#        ;;
#
#        Debian)
#            osSudo "${ROOT_USER}" systemctl start bitcoin
#            osSudo "${ROOT_USER}" systemctl start electrs
#            osSudo "${ROOT_USER}" journalctl --no-pager --unit bitcoin
#        ;;
#    esac
#fi
#
#if [ "${BITCOIN_TESTNET_ENABLE}" = ON ];then
#    echo "[*] Starting Bitcoin Mainnet"
#    case $OS in
#
#        FreeBSD)
#        ;;
#
#        Debian)
#            echo "[*] Starting Bitcoin Testnet"
#            osSudo "${ROOT_USER}" systemctl start bitcoin-testnet
#            osSudo "${ROOT_USER}" systemctl start electrs-testnet
#            osSudo "${ROOT_USER}" journalctl --no-pager --unit bitcoin-testnet
#    esac
#fi
#if [ "${ELEMENTS_LIQUID_ENABLE}" = ON ];then
#    case $OS in
#
#        FreeBSD)
#            echo "[*] Starting Elements Liquid"
#            osSudo "${ELEMENTS_USER}" sh -c "grep @reboot ${MEMPOOL_HOME}/${MEMPOOL_REPO_NAME}/production/elements.crontab|cut -d ';' -f2|zsh"
#        ;;
#
#        Debian)
#            echo "[*] Starting Elements Liquid"
#            osSudo "${ROOT_USER}" systemctl start liquid
#            osSudo "${ROOT_USER}" systemctl start electrs-liquid
#            osSudo "${ROOT_USER}" journalctl --no-pager --unit liquid
#    esac
#fi

#osSudo "${ROOT_USER}" tail "${BITCOIN_HOME}/debug.log"

##### OS notes

#echo "[*] Adding notes to motd"
#osSudo "${ROOT_USER}" sh -c 'echo " " >> /etc/motd'

##### OS firewall

#case $OS in
#
#    FreeBSD)
#    ;;
#
#    Debian)
#        echo "[*] Preparing firewall"
#        osSudo "${ROOT_USER}" ufw default deny incoming
#        osSudo "${ROOT_USER}" ufw default allow outgoing
#        osSudo "${ROOT_USER}" ufw allow from any to any port ${BITCOIN_MAINNET_P2P_PORT} proto tcp
#        osSudo "${ROOT_USER}" ufw allow from any to any port ${BITCOIN_TESTNET_P2P_PORT} proto tcp
#        osSudo "${ROOT_USER}" ufw allow from any to any port ${ELEMENTS_LIQUID_P2P_PORT} proto tcp
#    ;;
#esac

##### finish

if [ "${TOR_INSTALL}" = ON ];then
    echo "Your auto-generated Tor addresses are:"
    echo "${NGINX_MEMPOOL_ONION}"
    echo "${NGINX_BISQ_ONION}"
    echo "${NGINX_LIQUID_ONION}"
fi

echo
echo 'Please reboot to start all the services.'
echo '[*] Done!'

exit 0
