#!/bin/sh /etc/rc.common
# rinetd init script
# Copyright (C) 2009 OpenWrt.org

START=80

SSD=start-stop-daemon
BIN=/usr/sbin/rinetd
CFG=/var/etc/rinetd.conf
PID=/var/run/rinetd.pid

common_add() {
	local cfg="$1"
	local logfile logcommon allow deny match

	config_get      logfile   "$cfg" logfile
	config_get_bool logcommon "$cfg" logcommon 0

	[ -n "$logfile" ] && {
		echo "logfile $logfile" >> $CFG
		[ "$logcommon" -gt 0 ] && echo "logcommon" >> $CFG
	}

	config_get allow "$cfg" allow
	config_get deny  "$cfg" deny

	for match in $allow; do
		echo "allow $match" >> $CFG
	done

	for match in $deny; do
		echo "deny $match" >> $CFG
	done
}

forward_add() {
	local cfg="$1"
	local bindaddr bindport connaddr connport

	config_get bindaddr "$cfg" bindaddress
	config_get bindport "$cfg" bindport
	config_get connaddr "$cfg" connectaddress
	config_get connport "$cfg" connectport

	[ -n "$bindaddr" ] && [ -n "$connaddr" ] && \
	[ -n "$bindport" ] && [ -n "$connport" ] && \
		echo "$bindaddr $bindport $connaddr $connport" >> $CFG
}

start() {
	mkdir -p /var/etc /var/run
	
	echo "# This file is autogenerated, use /etc/config/rinetd" > $CFG
	config_load rinetd
	config_foreach common_add common
	config_foreach forward_add forwarding

	$SSD -S -q -x $BIN -- -c $CFG
}

stop() {
	$SSD -K -q -p $PID -x $BIN
	rm -f $PID $CFG
}

reload() {
	$SSD -K -q -p $PID -x $BIN -s 1 
}
