#!/bin/sh
# ============================================================================
#
# This file is part of the 'RandomTools for zypkgs' package
# 
# This program is free software; you can redistribute it and/or modify it 
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# Author: Mijzelf <Mijzelf@live.com>
#
# ============================================================================
#
PKGNAME="MuninLite"
PKG_ROOT="/usr/local/zy-pkgs"
CONFIG_DIR="${PKG_ROOT}/config/${PKGNAME}"
CONFIG_FILE="${CONFIG_DIR}/config"

IsUpgrading()
{
	if cat ${PKG_ROOT}/tmp/zypkg.log | grep "\[MuninLite\]" | tail | grep "Upgrade Mode" >/dev/null
	then
		return 0
	fi
	return 1
}

Log()
{
	[ -f /tmp/${PKGNAME}.log ] && echo "` date `: $@" >>/tmp/${PKGNAME}.log
}

Status()
{
	if [ ! -f ${CONFIG_FILE} ] ; then
		mkdir -p ${CONFIG_DIR}
		echo "Disabled" >${CONFIG_FILE}
	fi
	cat ${CONFIG_FILE}
}

GetLink()
{
    echo
}

Startup()
{
	local STATUS=` Status `
	[ "$STATUS" != "Enabled" ] && return 0
	
	local inetd_conf=/tmp/.MetaRepository/etc/inetd.conf
	[ ! -f $inetd_conf ] && return 0
	
	if grep ^4949 $inetd_conf >/dev/null
	then
		return 0
	fi
	
	echo "4949	stream	tcp	nowait	nobody	/usr/local/zy-pkgs/bin/munin-node	munin-node" >>$inetd_conf
	killall -HUP "busybox-metarepo"
	
	# Get i2cget to work
	[ -x /sbin/i2cget -a -e /dev/i2c-0 ] && chmod +s /sbin/i2cget
	
	# Get ethtool to work
	chmod +s /sbin/ethtool
	ln -s /sbin/ethtool /bin/ethtool
	
}

Shutdown()
{
	local inetd_conf=/tmp/.MetaRepository/etc/inetd.conf

	if ! grep ^4949 $inetd_conf >/dev/null
	then
		return 0
	fi
	
	grep -v ^4949 $inetd_conf >${inetd_conf}.new
	mv ${inetd_conf}.new $inetd_conf
	
	killall -HUP "busybox-metarepo"
}

Disable()
{
	Shutdown
	mkdir -p ${CONFIG_DIR}
	echo "Disabled" >${CONFIG_FILE}
}

Enable()
{
	mkdir -p ${CONFIG_DIR}
	echo "Enabled" >${CONFIG_FILE}
	Startup 
}

Log $0 $@

case $1 in
	getlink)
		GetLink
		;;
	status)
		Status
		;;
	startup)
		Startup
		;;
	shutdown)
		Shutdown
		;;
	enable)
		Enable
		;;
	disable)
		Disable
		;;
esac

exit 0
