#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: pepecoin
# REQUIRE: LOGIN
# KEYWORD: shutdown

#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# pepecoin_enable (bool):	Set to NO by default.
#				Set it to YES to enable pepecoin.
# pepecoin_config (path):	Set to /usr/local/etc/pepecoin.conf
#				by default.
# pepecoin_user:	The user account pepecoin daemon runs as
#				It uses 'pepecoin' user by default.
# pepecoin_group:	The group account pepecoin daemon runs as
#				It uses 'pepecoin' group by default.
# pepecoin_datadir (str):	Default to "/var/db/pepecoin"
#				Base data directory.

. /etc/rc.subr

name=pepecoin
rcvar=pepecoin_enable

load_rc_config $name

: ${pepecoin_enable:=NO}
: ${pepecoin_config=/usr/local/etc/pepecoin.conf}
: ${pepecoin_datadir=/var/db/pepecoin}
: ${pepecoin_user="root"}
: ${pepecoin_group="wheel"}

required_files=${pepecoin_config}
command=/usr/local/bin/pepecoind
cli_command=/usr/local/bin/pepecoin-cli
pepecoin_chdir=${pepecoin_datadir}
pidfile="${pepecoin_datadir}/pepecoind.pid"
stop_cmd=pepecoin_stop
command_args="-conf=${pepecoin_config} -datadir=${pepecoin_datadir} -noupnp -daemon -pid=${pidfile}"
start_precmd="${name}_prestart"
reindex_cmd=pepecoin_reindex
extra_commands="reindex"

pepecoin_create_datadir()
{
	echo "Creating data directory"
	eval mkdir -p ${pepecoin_datadir}
	[ $? -eq 0 ] && chown -R ${pepecoin_user}:${pepecoin_group} ${pepecoin_datadir}
}

pepecoin_prestart()
{
	if [ ! -d "${pepecoin_datadir}/." ]; then
		pepecoin_create_datadir || return 1
	fi
}

pepecoin_requirepidfile()
{
	if [ ! "0`check_pidfile ${pidfile} ${command}`" -gt 1 ]; then
		echo "${name} not running? (check $pidfile)."
		exit 1
	fi
}

pepecoin_stop()
{
    pepecoin_requirepidfile

	echo "Stopping ${name}."
	eval ${cli_command} -conf=${pepecoin_config} -datadir=${pepecoin_datadir} stop
	wait_for_pids ${rc_pid}
}

pepecoin_reindex()
{
	if [ -z "$rc_fast" -a -n "$rc_pid" ]; then
	    pepecoin_stop
	fi

	echo "Reindexing ${name} blockchain."
	command_args="${command_args} -reindex"
	eval ${command} ${command_args}
}

load_rc_config $name
run_rc_command "$1"
