#!/bin/sh

if [ -f "/etc/nginx/luci_nginx.conf" ] && [ -f "/etc/nginx/nginx.conf" ]; then
	if [ ! "$(cat '/etc/nginx/nginx.conf' | grep 'luci_uwsgi.conf')" ]; then
		mv /etc/nginx/nginx.conf /etc/nginx/nginx.conf_old
		mv /etc/nginx/luci_nginx.conf /etc/nginx/nginx.conf
		core_number=$(grep -c ^processor /proc/cpuinfo)
		sed -i "3s/.*/worker_processes  "$core_number";/" /etc/nginx/nginx.conf
		if [ -n "$(pgrep uhttpd)" ]; then
			/etc/init.d/uhttpd stop
			/etc/init.d/uhttpd disable
		fi
		if [ -n "$(pgrep nginx)" ]; then
			/etc/init.d/nginx restart
		else
			/etc/init.d/nginx start
		fi
		if [ -n "$(pgrep uwsgi)" ]; then
			/etc/init.d/uwsgi restart
		else
			/etc/init.d/uwsgi start
		fi
	else
		rm /etc/nginx/luci_nginx.conf
	fi
fi

if nginx -V 2>&1 | grep -q ubus; then
	if [ -z "$(cat /etc/nginx/luci_uwsgi.conf | grep ubus)" ]; then
		cat <<EOT >> /etc/nginx/luci_uwsgi.conf

location /ubus {
        ubus_interpreter;
        ubus_socket_path /var/run/ubus/ubus.sock;
        ubus_parallel_req 2;
}
EOT
	fi
fi

grep -q /var/run/ubus.sock /etc/nginx/conf.d/luci.locations &&
	sed -i 's#/var/run/ubus.sock#/var/run/ubus/ubus.sock#' /etc/nginx/conf.d/luci.locations

if [ -x /etc/init.d/uhttpd ]; then
        /etc/init.d/uhttpd disable
        if [ -n "$(pgrep uhttpd)" ]; then
                /etc/init.d/uhttpd stop
        fi
fi

/etc/init.d/nginx enable
if [ -n "$(pgrep nginx)" ]; then
        /etc/init.d/nginx restart
else
        /etc/init.d/nginx start
fi

/etc/init.d/uwsgi enable
if [ -n "$(pgrep uwsgi)" ]; then
        /etc/init.d/uwsgi restart
else
        /etc/init.d/uwsgi start
fi


exit 0
