#!/bin/sh

. /usr/share/libubox/jshn.sh

get_nginx_status() {
	port="${1}"
	nginx_pid=$(pgrep "nginx: master process")

	json_init
	if [ -z "${nginx_pid}" ]; then
		json_add_string "server_status" "Error"
		json_dump
		return
	fi

	state="Error"
	netstat -nltp | grep "${nginx_pid}/uci.conf" | awk '{print $4}' > /tmp/http_status
	while read server; do
		if [ -z "${server}" ]; then
			continue
		fi

		sport=$(echo "${server##*:}")
		if [ "${sport}" -eq "${port}" ]; then
			state="Up"
			break
		fi
	done < /tmp/http_status

	rm -rf /tmp/http_status

	json_add_string "server_status" "${state}"
	json_dump
	return
}

get_nginx_session_list() {
	netstat -ntp | grep nginx | awk '{print $4,$5}' > /tmp/http_session

	json_init
	json_add_array "http_sessions"
	while read server client; do
		if [ -z "${server}" ] || [ -z "${client}" ]; then
			continue
		fi

		sport=$(echo "${server##*:}")
		cip=$(echo "${client}" | sed 's/:[^:]*$//g')
		cport=$(echo "${client##*:}")

		json_add_object ""
		json_add_string "server_port" "${sport}"
		json_add_string "client_ip" "${cip}"
		json_add_string "client_port" "${cport}"
		json_close_object
	done < /tmp/http_session

	json_close_array

	json_dump

	rm -rf /tmp/http_session
	return
}

case "$1" in
	list)
		echo '{ "http_session": {}, "http_status": {"port":"String"} }'
	;;
	call)
		case "$2" in
			http_session)
				out="$(get_nginx_session_list)"
				if [ -z "${out}" ]; then
					echo '{}'
				else
					echo "$out"
				fi
			;;
			http_status)
				read -r input

				json_load "${input}"
				json_get_var port "port"
				json_cleanup

				out="$(get_nginx_status "${port}")"
				if [ -z "${out}" ]; then
					echo '{}'
				else
					echo "$out"
				fi
			;;
		esac
	;;
esac
