#!/bin/sh
# RPCD backend for MagicMirror2 LuCI app

CONFIG="magicmirror2"
CONTAINER="secbx-magicmirror"

uci_get() { uci -q get ${CONFIG}.main.$1; }

get_status() {
	local enabled=$(uci_get enabled)
	local port=$(uci_get port)
	local data_path=$(uci_get data_path)

	local docker_available=0
	command -v docker >/dev/null 2>&1 && docker_available=1

	local running=0
	if [ "$docker_available" = "1" ]; then
		docker ps --filter "name=$CONTAINER" --format "{{.Names}}" 2>/dev/null | grep -q "$CONTAINER" && running=1
	fi

	local installed=0
	[ "$docker_available" = "1" ] && docker images --format "{{.Repository}}" 2>/dev/null | grep -q "magicmirror" && installed=1

	cat <<EOFJ
{
	"enabled": $([ "$enabled" = "1" ] && echo "true" || echo "false"),
	"running": $([ "$running" = "1" ] && echo "true" || echo "false"),
	"installed": $([ "$installed" = "1" ] && echo "true" || echo "false"),
	"docker_available": $([ "$docker_available" = "1" ] && echo "true" || echo "false"),
	"port": ${port:-8080},
	"data_path": "${data_path:-/srv/magicmirror}"
}
EOFJ
}

do_install() {
	command -v magicmirror2ctl >/dev/null 2>&1 && { magicmirror2ctl install >/tmp/mm2-install.log 2>&1 & echo '{"success":true,"message":"Installing"}'; } || echo '{"success":false,"error":"magicmirror2ctl not found"}'
}

do_start() { [ -x /etc/init.d/magicmirror2 ] && /etc/init.d/magicmirror2 start >/dev/null 2>&1; echo '{"success":true}'; }
do_stop() { [ -x /etc/init.d/magicmirror2 ] && /etc/init.d/magicmirror2 stop >/dev/null 2>&1; echo '{"success":true}'; }
do_restart() { [ -x /etc/init.d/magicmirror2 ] && /etc/init.d/magicmirror2 restart >/dev/null 2>&1; echo '{"success":true}'; }

list_methods() { cat <<'EOFM'
{"status":{},"install":{},"start":{},"stop":{},"restart":{}}
EOFM
}

case "$1" in
	list) list_methods ;;
	call) case "$2" in status) get_status ;; install) do_install ;; start) do_start ;; stop) do_stop ;; restart) do_restart ;; *) echo '{"error":"Unknown method"}' ;; esac ;;
	*) echo '{"error":"Unknown command"}' ;;
esac
