#!/bin/bash
# App Center run control: start | stop | status (status: 0 running, 3 not).
#
# start enables the unit too, so the agent comes back on its own after a
# reboot (App Center's own boot-time start is not ordered after the network
# and is not retried). stop disables it, so a stopped app stays stopped.

# shellcheck source=common
. "$(dirname "$0")/common"

case "${1:-}" in
start)
	log "start"
	require_root || exit 1
	if [ ! -e /dev/net/tun ]; then
		log "warning: /dev/net/tun missing (VM install without TUN?)"
	fi
	install_unit || { user_msg "安装系统服务失败，详见 $LOG"; exit 1; }
	systemctl enable --now "$UNIT" >>"$LOG" 2>&1
	# Report failure only if the service really does not come up.
	for _ in $(seq 1 15); do
		unit_active && [ -S "$TARGET/app.sock" ] && exit 0
		sleep 1
	done
	if unit_active; then
		log "started (gateway socket not up yet)"
		exit 0
	fi
	user_msg "EdNovas 服务启动失败，可在 SSH 中执行 journalctl -u $UNIT -n 50 查看原因"
	exit 1
	;;
stop)
	log "stop"
	systemctl disable --now "$UNIT" >>"$LOG" 2>&1
	exit 0
	;;
status)
	unit_active && exit 0
	exit 3
	;;
*)
	exit 1
	;;
esac
