#!/bin/sh
# RPCD backend for MagicMirror² Manager

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

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

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

get_modules_path() {
	local path
	path=$(get_config_value modules_path)
	echo "${path:-/srv/magicmirror/modules}"
}

get_config_path() {
	local path
	path=$(get_config_value config_path)
	echo "${path:-/srv/magicmirror/config}"
}

list_modules() {
	local modules_path
	modules_path=$(get_modules_path)

	json_init
	json_add_array "modules"

	if [ -d "$modules_path" ]; then
		for module_dir in "$modules_path"/MMM-*; do
			if [ -d "$module_dir" ]; then
				local module_name=$(basename "$module_dir")
				local description=""
				local author=""
				local version=""

				# Try to extract info from package.json
				if [ -f "$module_dir/package.json" ]; then
					description=$(jq -r '.description // ""' "$module_dir/package.json" 2>/dev/null)
					author=$(jq -r '.author // ""' "$module_dir/package.json" 2>/dev/null)
					version=$(jq -r '.version // ""' "$module_dir/package.json" 2>/dev/null)
				fi

				json_add_object
				json_add_string "name" "$module_name"
				json_add_string "description" "$description"
				json_add_string "author" "$author"
				json_add_string "version" "$version"
				json_add_string "path" "$module_dir"
				json_close_object
			fi
		done
	fi

	json_close_array
}

get_config_content() {
	local config_path
	config_path=$(get_config_path)
	local config_file="$config_path/config.js"

	if [ -f "$config_file" ]; then
		cat "$config_file"
	else
		echo ""
	fi
}

case "$1" in
	list)
		json_init
		json_add_object "getStatus"
		json_close_object
		json_add_object "listModules"
		json_close_object
		json_add_object "getConfig"
		json_close_object
		json_add_object "installModule"
			json_add_string "url" "string"
		json_close_object
		json_add_object "removeModule"
			json_add_string "name" "string"
		json_close_object
		json_add_object "updateModule"
			json_add_string "name" "string"
		json_close_object
		json_add_object "getModuleConfig"
			json_add_string "name" "string"
		json_close_object
		json_add_object "saveConfig"
			json_add_string "content" "string"
		json_close_object
		json_add_object "restartService"
		json_close_object
		json_dump
		;;

	call)
		case "$2" in
			getStatus)
				# Get service status
				json_init
				json_add_boolean "success" 1

				# Check if container is running
				local running=0
				docker ps --filter "name=$CONTAINER" --format '{{.Names}}' 2>/dev/null | grep -q "$CONTAINER" && running=1

				# Get config values
				config_load "$CONFIG"
				local enabled port
				config_get enabled main enabled "0"
				config_get port main port "8080"

				json_add_object "status"
					json_add_boolean "running" "$running"
					json_add_boolean "enabled" "$enabled"
					json_add_string "port" "$port"
					json_add_string "container" "$CONTAINER"
				json_close_object

				# Count modules
				local modules_count=0
				local modules_path
				modules_path=$(get_modules_path)
				if [ -d "$modules_path" ]; then
					modules_count=$(find "$modules_path" -maxdepth 1 -name "MMM-*" -type d 2>/dev/null | wc -l)
				fi

				json_add_object "stats"
					json_add_int "modules_installed" "$modules_count"
				json_close_object

				json_dump
				;;

			listModules)
				json_init
				json_add_boolean "success" 1
				list_modules
				json_dump
				;;

			getConfig)
				json_init
				json_add_boolean "success" 1
				json_add_string "content" "$(get_config_content)"
				json_dump
				;;

			installModule)
				read input
				json_load "$input"

				local url
				json_get_var url url

				if [ -z "$url" ]; then
					json_init
					json_add_boolean "success" 0
					json_add_string "error" "URL is required"
					json_dump
					exit 0
				fi

				# Install module in background
				/usr/sbin/magicmirrorctl module install "$url" >/tmp/mm-install.log 2>&1 &

				json_init
				json_add_boolean "success" 1
				json_add_string "message" "Module installation started"
				json_dump
				;;

			removeModule)
				read input
				json_load "$input"

				local name
				json_get_var name name

				if [ -z "$name" ]; then
					json_init
					json_add_boolean "success" 0
					json_add_string "error" "Module name is required"
					json_dump
					exit 0
				fi

				# Remove module
				/usr/sbin/magicmirrorctl module remove "$name" >/dev/null 2>&1

				json_init
				json_add_boolean "success" 1
				json_add_string "message" "Module removed"
				json_dump
				;;

			updateModule)
				read input
				json_load "$input"

				local name
				json_get_var name name

				if [ -z "$name" ]; then
					json_init
					json_add_boolean "success" 0
					json_add_string "error" "Module name is required"
					json_dump
					exit 0
				fi

				# Update module in background
				/usr/sbin/magicmirrorctl module update "$name" >/tmp/mm-update.log 2>&1 &

				json_init
				json_add_boolean "success" 1
				json_add_string "message" "Module update started"
				json_dump
				;;

			getModuleConfig)
				read input
				json_load "$input"

				local name
				json_get_var name name

				if [ -z "$name" ]; then
					json_init
					json_add_boolean "success" 0
					json_add_string "error" "Module name is required"
					json_dump
					exit 0
				fi

				local modules_path
				modules_path=$(get_modules_path)
				local readme_content=""

				if [ -f "$modules_path/$name/README.md" ]; then
					readme_content=$(cat "$modules_path/$name/README.md")
				fi

				json_init
				json_add_boolean "success" 1
				json_add_string "readme" "$readme_content"
				json_dump
				;;

			saveConfig)
				read input
				json_load "$input"

				local content
				json_get_var content content

				if [ -z "$content" ]; then
					json_init
					json_add_boolean "success" 0
					json_add_string "error" "Content is required"
					json_dump
					exit 0
				fi

				local config_path
				config_path=$(get_config_path)
				local config_file="$config_path/config.js"

				# Backup current config
				if [ -f "$config_file" ]; then
					cp "$config_file" "$config_file.backup.$(date +%Y%m%d_%H%M%S)"
				fi

				# Save new config
				echo "$content" > "$config_file"

				json_init
				json_add_boolean "success" 1
				json_add_string "message" "Configuration saved"
				json_dump
				;;

			restartService)
				# Restart MagicMirror service
				/etc/init.d/magicmirror restart >/dev/null 2>&1 &

				json_init
				json_add_boolean "success" 1
				json_add_string "message" "Service restart initiated"
				json_dump
				;;

			*)
				json_init
				json_add_boolean "success" 0
				json_add_string "error" "Unknown method"
				json_dump
				;;
		esac
		;;
esac
