#!/bin/bash
# Start/stop the Octez Bakers and Accusers
#
### BEGIN INIT INFO
# Provides:          octez-smartrollup
# Required-Start:    
# Required-Stop:     
# Should-Start:      $network $named 
# Should-Stop:       $network $named 
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: The Octez Smart Rollup daemons
# Description:       The Octez Smart Rollup daemons manage a rollup on the
#		     Tezos network.
### END INIT INFO

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DESC="octez smartrollup"
NAME=octez-smartrollup
PIDDIR=/var/run/tezos
SCRIPTNAME=/etc/init.d/"$NAME"

if [ -f "/lib/lsb/init-functions" ]; then
        . /lib/lsb/init-functions
else
        . /etc/rc.d/init.d/functions
fi

# Defaults
user=tezos
group=tezos
nodedir=/var/tezos/.tezos-node
clientdir=/var/tezos/.tezos-client
rollupdatadir=/var/tezos/.tezos-smart-rollup-node
logdir=/var/log/tezos
rotateonstart=yes
nodeaddr=127.0.0.1
rpcport=8732
othercliopts_smartrollup=""

[ -r /etc/octez/node.conf ] && . /etc/octez/node.conf
[ -r /etc/octez/smartrollup.conf ] && . /etc/octez/smartrollup.conf

[ -z "$nodeurl" ] && nodeurl="http://$nodeaddr:$rpcport"

logfile="${logdir}/smartrollup.log"
sr="/usr/bin/octez-smart-rollup-node"

initial_checks()
{
	mkdir -p ${PIDDIR}
	chown $user:$group ${PIDDIR}

	mkdir -p ${logdir}
	chown $user:$group ${logdir}

	if [ ! -f "$rollupdatadir/config.json" ]; then
		echo "Rollup not configured" >&2
		exit 3
	fi
	
}

rotate_logs ()
{
	if [ ${rotateonstart} = "yes" ]; then
		[ -f "${logfile}" ] && mv -f "${logfile}" "${logfile}.1"
	fi
}

case "$1" in
start)	initial_checks
	rotate_logs
	su $user -c "${sr} -d "$clientdir" -E $nodeurl run --data-dir "$rollupdatadir" ${othercliopts_smartrollup} >> ${logfile} 2>&1 &"
	;;
stop)	
       	pkill -f octez-smart-rollup-node
        ;;
restart) 
        $0 stop
        $0 start
        ;;
reload|force-reload) 
        ;;
status)
	status_of_proc ${sr} $NAME || exit $?
	exit 0
        ;;
*)	echo "Usage: $0 {start|stop|status|restart|reload|force-reload}" >&2
        exit 2
        ;;
esac
exit 0
