#!/bin/sh -e

# Source debconf library.
. /usr/share/debconf/confmodule

# add random rpc password to bitcoin.conf
echo "rpcpassword=$(xxd -l 16 -p /dev/urandom)" >> /etc/bitcoincl/bitcoin.conf

# add users
adduser --system --group --quiet bitcoin

# cleanup permissions
chown root:root /usr/bin/bitcoincl*
chown root:root /lib/systemd/system/bitcoincld.service
chown root:root /etc/bitcoincl
chown bitcoin:bitcoin /etc/bitcoincl/bitcoin.conf
chmod ug+r /etc/bitcoincl/bitcoin.conf
chmod u+w /etc/bitcoincl/bitcoin.conf
chmod o-rw /etc/bitcoincl/bitcoin.conf
chown -R bitcoin:bitcoin /var/lib/bitcoincl
chmod u+rwx /var/lib/bitcoincl

# enable and start bitcoincld service if systemctl exists and is executable
if [ -x "/bin/systemctl" ]; then
    db_input high bitcoincl/start_service || true
    db_go || true
    db_get bitcoincl/start_service
    if [ "$RET" = "true" ]; then
        echo "Enabling bitcoincld.service"
    	/bin/systemctl enable bitcoincld.service
        echo "Starting bitcoincld.service"
    	/bin/systemctl start bitcoincld.service
    else
        echo "The bitcoincld.service NOT enabled or started."
    fi
else
    echo "The file '/bin/systemctl' is not executable or found, bitcoincld service not automatically enabled or started"
fi
