#!/bin/sh
# handwash 应用开机自启(由 /oem/usr/bin/RkLunch.sh 的 rcS 调用, 传参 start)
#
# 注意: 本文件由 handwash 仓库 scripts/package_image.sh 自动安装/更新,
#       勿在 SDK 内手改; 修改源头: handwash 仓库
#       sdk_integration/project/app/handwash/S99handwash
#
# 时序说明: rcS 在 insmod_ko.sh(加载 ko)之前执行, 所以这里 fork 后台等待:
#   1) 等 rockit ko 就绪(/dev/mpi/vvi)
#   2) 拉起 rkaiq_3A_server(ISP 出帧前提)
#   3) 在工作目录 /oem/usr/share/handwash 启动 handwash_app(conf/models 用相对路径)

APP_BIN=/oem/usr/bin/handwash_app
APP_DIR=/oem/usr/share/handwash
LOG_DIR=/root/handwash
LOG=$LOG_DIR/handwash.log

is_running()
{
	ps | grep -v grep | grep -q handwash_app
}

launch()
{
	mkdir -p $LOG_DIR

	i=0
	while [ ! -e /dev/mpi/vvi ] && [ $i -lt 60 ]; do
		i=$((i+1)); sleep 0.5
	done
	[ -e /dev/mpi/vvi ] || echo "[handwash] warn: /dev/mpi/vvi 未就绪, 仍尝试启动" >> $LOG

	if ! ps | grep -v grep | grep -q rkaiq_3A_server; then
		echo "[handwash] start rkaiq_3A_server" >> $LOG
		[ -x /oem/usr/bin/rkaiq_3A_server ] && \
			/oem/usr/bin/rkaiq_3A_server >> /tmp/rkaiq_3A.log 2>&1 &
		sleep 3
	fi

	cd $APP_DIR || { echo "[handwash] $APP_DIR 不存在" >> $LOG; return 1; }
	echo "[handwash] $(date '+%F %T') app starting..." >> $LOG
	LD_LIBRARY_PATH=/oem/usr/lib:$LD_LIBRARY_PATH \
		$APP_BIN --conf conf/handwash.conf >> $LOG 2>&1 &
}

case "$1" in
start)
	is_running && exit 0
	launch &
	;;
stop)
	killall handwash_app 2>/dev/null
	;;
restart|reload)
	killall handwash_app 2>/dev/null
	sleep 1
	launch &
	;;
*)
	echo "usage: $0 {start|stop|restart}"
	;;
esac
