#!/bin/sh /etc/rc.common
#
# Copyright (C) 2025 sirpdboy herboy2008@gmail.com https://github.com/sirpdboy/luci-app-eqosplus
#

START=99
USE_PROCD=1

NAME=eqosplus
LOCK="/var/lock/$NAME.lock"
CR=/etc/crontabs/root

start_instance() {
	 procd_open_instance
	 procd_set_param command /usr/bin/eqosplusctrl
	 procd_set_param respawn
	 procd_set_param stderr 1
	 procd_close_instance
}

_eqosplus_start() {
	 if [ "$(grep -c 'option enable .1.' /etc/config/$NAME 2>/dev/null)" -gt "0" ]; then
	 if [ x$(uci -q get turboacc.config.sw_flow) = 'x1' ] || [ x$(uci -q get turboacc.config.sfe_flow) = 'x1' ]  ;then
	         uci -q set turboacc.config.sw_flow='0'
	         uci -q set turboacc.config.sfe_flow='0'
		 uci -q set turboacc.config.hw_flow='0'
		 uci commit turboacc
		 /etc/init.d/turboacc restart
	  fi
	    touch $LOCK
	    eqosplus start
	    start_instance
	    (crontab -l ; echo "00 1 * * * /etc/init.d/eqosplus start") | sort - | uniq - | crontab -
	 fi
}

start_service(){
	[ -f $LOCK ] && exit
	stop_service
	_eqosplus_start
	rm -f $LOCK
}

service_triggers() {
 	 procd_add_reload_trigger 'eqosplus'
}

stop_service(){
	kill -9 $(busybox ps -w | grep 'eqosplusctrl' | grep -v 'grep' | awk '{print $1}') >/dev/null 2>&1
	sed -i '/eqosplus/d' $CR >/dev/null 2>&1
	rm -f $LOCK 2>/dev/null
	eqosplus stop
}


reload_service() {
	restart
}
