#!/bin/sh

# PROVIDE: lightningd
# REQUIRE: LOGIN bitcoind cleanvar
# KEYWORD: shutdown

# Add the following to %%LOCALBASE%%/etc/rc.conf.d/lightningd to influence
# the behavior of this script (default values are listed):
#
# lightningd_enable="NO"  # change to "YES" to enable
# lightningd_user="%%U%%"
# lightningd_group="%%G%%"
# lightningd_base_dir="%%LIGHTNINGD_BASE_DIR%%"
# lightningd_network="bitcoin"
# lightningd_conf="%%PREFIX%%/etc/lightningd-${lightningd_network}.conf"
# lightningd_extra_args=""  # See lightningd --help

. /etc/rc.subr

name="lightningd"
rcvar=lightningd_enable

load_rc_config ${name}

# If clnrest plugin is enabled it fails to load with OpenSSL 3.0: RuntimeError: OpenSSL 3.0's legacy provider failed to load. This is a fatal error by default, but cryptography supports running without legacy algorithms by setting the environment variable CRYPTOGRAPHY_OPENSSL_NO_LEGACY. If you did not expect this error, you have likely made a mistake with your OpenSSL configuration.
export CRYPTOGRAPHY_OPENSSL_NO_LEGACY=1

: ${lightningd_enable:="NO"}
: ${lightningd_user:="%%U%%"}
: ${lightningd_group:="%%G%%"}
: ${lightningd_base_dir:="%%LIGHTNINGD_BASE_DIR%%"}
: ${lightningd_network:="bitcoin"}
: ${lightningd_conf:="%%PREFIX%%/etc/${name}-${lightningd_network}.conf"}

start_precmd="lightningd_start_precmd"
pidfile="${lightningd_base_dir}/lightningd-${lightningd_network}.pid"
command="%%PREFIX%%/bin/lightningd"
command_args=""
command_args="${command_args} --lightning-dir=${lightningd_base_dir}"
command_args="${command_args} --network=${lightningd_network}"
command_args="${command_args} --daemon"
# service(8) would execute us with LOCALBASE stripped out from PATH,
# thus specify the full path to bitcoin-cli.
command_args="${command_args} --bitcoin-cli=%%LOCALBASE%%/bin/bitcoin-cli"
# bitcoin-cli(1) tries to create its "datadir" (by default ${HOME}/.bitcoin)
# if it does not exist. Provide something that already exists to avoid the
# creation of unnecessary empty directories.
command_args="${command_args} --bitcoin-datadir=${lightningd_base_dir}"

if [ -e "${lightningd_conf}" ] ; then
	command_args="${command_args} --conf=${lightningd_conf}"
fi

command_args="${command_args} ${lightningd_extra_args}"

check_bitcoind_ready()
{
    %%LOCALBASE%%/bin/bitcoin-cli \
        -rpcconnect=${bitcoin_addr}${bitcoin_port:+":"}${bitcoin_port} \
        -rpcuser=${bitcoin_user} \
        -stdinrpcpass \
        echo itworks <<PASS
${bitcoin_pass}
PASS
}

lightningd_start_precmd()
{
    # Wait for bitcoind to be fully operational. lightningd would quit (refuse
    # to start) if it can't talk to bitcoind via its RPC.
    bitcoin_addr="`grep ^bitcoin-rpcconnect= "${lightningd_conf}" |cut -f 2- -d =`"
    bitcoin_port="`grep ^bitcoin-rpcport= "${lightningd_conf}" |cut -f 2- -d =`"
    bitcoin_user="`grep ^bitcoin-rpcuser= "${lightningd_conf}" |cut -f 2- -d =`"
    bitcoin_pass="`grep ^bitcoin-rpcpassword= "${lightningd_conf}" |cut -f 2- -d =`"

    i=20
    while : ; do
        if [ $i -eq 0 ] ; then
            # Show errors from last attempt.
            if ! check_bitcoind_ready ; then
                echo "Failed: bitcoind did not start serving RPC, starting lightningd anyway"
            fi
            break
        else
            if check_bitcoind_ready > /dev/null 2>&1; then
                break
            fi
        fi
        echo "Waiting for bitcoind to start serving RPC, lightningd cannot start without it $i"
        sleep 1
        i=$((i - 1))
    done
}

run_rc_command "$1"
