#!/bin/sh /etc/rc.common
# Copyright (C) 2013-2017 OpenWrt.org

START=60
USE_PROCD=1

_log() {
	logger -p daemon.info -t prometheus-node-exporter-ucode "$@"
}

start_service() {
	. /lib/functions/network.sh

	local interface port bind4 bind6

	config_load prometheus-node-exporter-ucode.main
	config_get interface "main" listen_interface "loopback"
	config_get port "main" listen_port 9101
	config_get keepalive "main" http_keepalive 70

	[ "$interface" = "*" ] || {
		network_get_ipaddr  bind4 "$interface"
		network_get_ipaddr6 bind6 "$interface"
		[ -n "$bind4$bind6" ] || {
			_log "defering start until listen interface $interface becomes ready"
			return 0
		}
	}

	procd_open_instance

	procd_set_param command /usr/sbin/uhttpd -f -c /dev/null -h /dev/null -S -D -o /metrics -O /usr/share/ucode/node-exporter/metrics.uc

	if [ "$interface" = "*" ]; then
		procd_append_param command -p $port
	else
		[ -n "$bind4" ] && procd_append_param command -p $bind4:$port
		[ -n "$bind6" ] && procd_append_param command -p [$bind6]:$port
	fi
	[ $keepalive -gt 0 ] && procd_append_param command -k $keepalive

	procd_add_jail prometheus-node-exporter-ucode log procfs sysfs ubus
	procd_add_jail_mount "/usr/lib/uhttpd_ucode.so"
	procd_add_jail_mount "/lib/libubus.so*"
	procd_add_jail_mount "/lib/libuci.so*"
	procd_add_jail_mount "/usr/lib/ucode"
	procd_add_jail_mount "/usr/lib/libnl*.so*"
	procd_add_jail_mount "/usr/share/ucode/node-exporter"
	procd_add_jail_mount "/etc/config"

	# TODO breaks the dsl collector?
	#procd_set_param user nobody
	#procd_set_param group nogroup
	procd_set_param no_new_privs 1

	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_set_param respawn

	procd_close_instance
}

service_triggers()
{
	local interface

	procd_add_reload_trigger "prometheus-node-exporter-ucode"

	config_load prometheus-node-exporter-ucode.main
	config_get interface "main" listen_interface "loopback"

	[ "$interface" = "*" ] || procd_add_reload_interface_trigger "$interface"
}
