#!/bin/sh
### BEGIN INIT INFO
# Provides:          breeze-core
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Breeze Core - self-hosted Midea AC control
### END INIT INFO
#
# Legacy SysV init script (uses start-stop-daemon, Debian-family).
# Install:  install -m 0755 deploy/init/sysv-breeze-core /etc/init.d/breeze-core
#           update-rc.d breeze-core defaults    # or: chkconfig --add breeze-core
#
# Prefer OpenRC / runit / supervisord if you have the choice — they handle
# respawn and logging for you. No systemd sandbox here: see HARDENING.md §7.

NAME=breeze-core
USER=breeze
HOME_DIR=/opt/breeze-core
HOST=192.168.1.10               # bind 127.0.0.1 behind a reverse proxy
PORT=8420
DAEMON="$HOME_DIR/venv/bin/uvicorn"
DAEMON_ARGS="meow_ac.app:app --host $HOST --port $PORT"
PIDFILE=/var/run/$NAME.pid
LOGFILE=/var/log/$NAME.log

export AC_CONFIG=/etc/breeze-core/config.json
export AC_DEVICES=/etc/breeze-core/devices.json
export AC_PROGRAMS=/etc/breeze-core/programs.json

case "$1" in
	start)
		echo "Starting $NAME"
		start-stop-daemon --start --background --make-pidfile --pidfile "$PIDFILE" \
			--chuid "$USER" --chdir "$HOME_DIR" \
			--startas /bin/sh -- -c "exec $DAEMON $DAEMON_ARGS >> $LOGFILE 2>&1"
		;;
	stop)
		echo "Stopping $NAME"
		start-stop-daemon --stop --pidfile "$PIDFILE" --retry INT/10/TERM/5 --oknodo
		rm -f "$PIDFILE"
		;;
	restart)
		"$0" stop; sleep 2; "$0" start
		;;
	status)
		if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
			echo "$NAME running (pid $(cat "$PIDFILE"))"
		else
			echo "$NAME not running"; exit 3
		fi
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"; exit 1
		;;
esac
exit 0
