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

START=99

USE_PROCD=1

CONFIGNAME="bandwidthd-php"
CONFIGFILE="/var/etc/bandwidthd-php.conf"

config_cb() {
	local cfg_type="$1"
	local cfg_name="$2"
	case "$cfg_type" in
	        $CONFIGNAME)
	                append cfgs "$cfg_name"
	        ;;
	esac
}

export_number() {
	local option="$1"
	local section="$2"
	local _loctmp
	paramstr=""
	config_get _loctmp "$section" "$option"
	if [ -n "$_loctmp" ]; then
		paramstr="${_loctmp}"
	fi
}

export_string() {
	local option="$1"
	local section="$2"
	local _loctmp
	paramstr=""
	config_get _loctmp "$section" "$option"
	if [ -n "$_loctmp" ]; then
		paramstr="${_loctmp}"
	fi
}

service_triggers()
{
        procd_add_reload_trigger $CONFIGNAME
}


start_service() {
	local conffile="<?php\n// auto-generated config file from /etc/config/${CONFIGNAME}\n"
        rm -f $CONFIGFILE
        touch $CONFIGFILE

	config_load $CONFIGNAME
	for cfg in $cfgs; do
		export_number dflt_width $cfg
		conffile="${conffile}define(\"DFLT_WIDTH\", ${paramstr:-"900"});\n"

		export_number dflt_height $cfg
       		conffile="${conffile}define(\"DFLT_HEIGHT\", ${paramstr:-"256"});\n"

		export_string dflt_interval $cfg
		conffile="${conffile}define(\"DFLT_INTERVAL\", ${paramstr:-"INT_DAILY"});\n\n"'$db_connect_string = "host='

		export_string host $cfg
		conffile="${conffile}${paramstr:-"127.0.0.1"} user="

		export_string user $cfg
		conffile="${conffile}${paramstr:-"postgres"} dbname="

		export_string dbname $cfg
		conffile="${conffile}${paramstr:-"bandwidthd"}"'"'"\n?>"
		[ -n "$conffile" ] && echo -e "$conffile" >>$CONFIGFILE
	done
}
