#!/bin/sh

. /lib/functions.sh
UCI_TEMPLATE="/etc/nginx/uci.conf.template"

if [ ! -f "/etc/config/mosquitto" ]; then
	logger -t sulu.ucidefault "Local mosquitto broker not available"
	return 1
fi

if [ ! -f "${UCI_TEMPLATE}" ]; then
	logger -t sulu.ucidefault "nginx utils not installed, sulu can't run"
	return 1
fi

update_nginx_uci_template()
{
	local port

	port="$(uci -q get mosquitto.sulu.port)"
	port="${port:-9009}"

	if ! grep -w "upstream websocket" ${UCI_TEMPLATE} | grep -wq "127.0.0.1:${port}"; then
		sed -i '/#UCI_HTTP_CONFIG$/i\   map $http_upgrade $connection_upgrade { default upgrade; "" close; }' ${UCI_TEMPLATE}
		sed -i "/#UCI_HTTP_CONFIG$/i\   upstream websocket { server 127.0.0.1:${port}; }" ${UCI_TEMPLATE}
	fi
}

add_sulu_config_to_mosquitto()
{
	uci_add mosquitto listener sulu
	uci_set mosquitto sulu enabled 1
	uci_set mosquitto sulu port '9009'
	uci_set mosquitto sulu no_remote_access '1'
	uci_set mosquitto sulu protocol 'websockets'
	uci_set mosquitto sulu auth_plugin '/usr/lib/mosquitto_auth_plugin.so'
	uci_set mosquitto sulu acl_file '/etc/sulu/mqtt.acl'
}

add_sulu_userinterface_uci()
{
	# check if sulu already configured
	if ! uci show userinterface| grep -q "path_prefix='/sulu'"; then
		uci_add userinterface http_access _sulu_s
		uci_set userinterface _sulu_s path_prefix '/sulu'
		uci_set userinterface _sulu_s port '8443'
		uci_set userinterface _sulu_s _nginx_include '/etc/sulu/nginx.locations'
		uci_set userinterface _sulu_s _nginx_uci_manage_ssl 'self-signed'
		uci_set userinterface _sulu_s _nginx_ssl_certificate '/etc/nginx/conf.d/_lan.crt'
		uci_set userinterface _sulu_s _nginx_ssl_certificate_key '/etc/nginx/conf.d/_lan.key'
		uci_set userinterface _sulu_s _nginx_ssl_session_cache 'none'
		uci_set userinterface _sulu_s _nginx_error_page '503 /maintenance.html'
		uci_set userinterface _sulu_s protocol 'HTTPS'
		uci_set userinterface _sulu_s role 'admin user'

		uci_add userinterface http_access _suluredirect
		uci_set userinterface _suluredirect redirect '_sulu_s'
		uci_set userinterface _suluredirect protocol 'HTTP'
		uci_set userinterface _suluredirect port "8080"
	fi
}

add_sulu_config_to_mosquitto
add_sulu_userinterface_uci
update_nginx_uci_template

/etc/sulu/sulu.sh
