#!/bin/sh /etc/rc.common
# Copyright (C) 2006 OpenWrt.org
START=50

BIN=lighttpd
DEFAULT=/etc/default/$BIN
LOG_D=/var/log/$BIN
RUN_D=/var/run
PID_F=$RUN_D/$BIN.pid

check_cfg_version() {
	CONF_FILE=/etc/lighttpd.conf
	CFG_VER=$(cat /rom$CONF_FILE | grep -E "^#CFG_VER =" 2>/dev/null || echo "#CFG_VER = 1000")
	CFG_VER=$(echo "$CFG_VER" | awk 'FS="[ =]+" {print $2}')	# current version in /rom/etc/lighttpd.conf
	
	cat $CONF_FILE | grep -q "CFG_VER = $CFG_VER" || {	# check config file version
		svr_port=$(cat $CONF_FILE | grep -E "[ ]*server.port[ ]*=" | grep -v -m 1 "#.*server.port" 2>/dev/null || echo "server.port = 80")
		svr_port=$(echo "$svr_port" | awk 'FS="[ =]+" {print $2}')
		cp "/rom$CONF_FILE" "$CONF_FILE"
		[ "$svr_port" != "80" ] && modify_lighttpd_cfgfile "server.port" $svr_port
	}
}

modify_lighttpd_cfgfile() {
	CFG_FILE=/etc/lighttpd.conf
	cat $CFG_FILE | grep -E "[ ]*server.port[ ]*=" | grep -v -m 1 "#.*server.port" 2>/dev/null || echo -e "\n\n$1 = $2\n\n" >> $CFG_FILE
	
	local str=$(cat $CFG_FILE | grep -E "[ ]*$1[ ]*=" | grep -v -m 1 "#.*$1")
	sed 's/'"$str"'/'"$1 = $2"'/' $CFG_FILE > /tmp/httpdcfg.dat
	test -s /tmp/httpdcfg.dat && cp /tmp/httpdcfg.dat $CFG_FILE
}

start() {
	check_cfg_version
	[ -f $DEFAULT ] && . $DEFAULT
	mkdir -p $LOG_D
	mkdir -p $RUN_D
	$BIN $OPTIONS
}

stop() {
	[ -f $PID_F ] && kill $(cat $PID_F)
}

