#!/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="Twonky"
PKG_ROOT="/usr/local/zy-pkgs"
CONFIG_DIR="${PKG_ROOT}/config/${PKGNAME}"
CONFIG_FILE="${CONFIG_DIR}/config"
TWONKYDIR=/usr/local/dmsf/
TWONKYSCRIPT=/usr/local/dmsf/mediaserver.sh

IsUpgrading()
{
	if cat ${PKG_ROOT}/tmp/zypkg.log | grep "\[Twonky\]" | 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()
{
	if /bin/ps | grep twonky | grep -v grep >/dev/null
	then
		local ADDR=`/sbin/ifconfig egiga0 | grep "inet addr" | tr -s ' '`
		echo  "http://`echo ${ADDR} | cut -d ' ' -f 2 | cut -d ':' -f 2`:9001"
	fi
}

Startup()
{
	local STATUS=` Status `
	[ "$STATUS" != "Enabled" ] && return 0
	
	local mytwonkydir=${PKG_ROOT}${TWONKYDIR}

	local restart=0
	if /bin/ps | grep twonky | grep -v grep >/dev/null
	then
		restart=1
		${TWONKYSCRIPT} stop
	fi
	
	mount --bind ${PKG_ROOT}${TWONKYDIR} $TWONKYDIR
	
	[ $restart -eq 1 ] && ${TWONKYSCRIPT} start
}

Shutdown()
{
	if grep "${TWONKYDIR}" /proc/mounts >/dev/null
	then
		local restart=0
		if /bin/ps | grep twonky | grep -v grep >/dev/null
		then
			restart=1
			${TWONKYSCRIPT} stop
		fi

		umount -l ${TWONKYDIR}

		[ $restart -eq 1 ] && ${TWONKYSCRIPT} start
	fi
}

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
