#!/bin/sh
# ============================================================================
#
# This file is part of the 'MetaRepository' 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>
#
# ============================================================================
PKG_NAME="MetaRepository"
THIS_SCRIPT="MetaRepository"
PKG_FIRMWARE=4

############################################################
## Check if we are in upgradig mode. From the point of view of the package
## an upgrade is a uninstall followed by a install. So if you want to preserve
## something over an upgrade, you have to detect it somehow
##
## Function sets PKG_UPGRADE > 0 when upgrading, 
## and PKG_UPGRADE=0 when not
############################################################
IsUpgrading()
{
	PKG_UPGRADING=0
	local dir=
	for dir in "/usr/local/zy-pkgs/" "/i-data/.system/zy-pkgs/"
	do
		local logfile=${dir}tmp/zypkg.log
		[ ! -f ${logfile} ] && continue

		local lastupdate=` grep "Upgrade Mode" ${logfile} | tail -n 1 | grep "\[${PKG_NAME}\]" | awk -v OFS=' ' '{print $1, $2}' `

	        [ "${lastupdate}" = "" ] && return 1

		local since1970=` TZ=GMT date -d "${lastupdate}" +%s `
		local now=`date +%s `
		local ago=""
		let ago=now-since1970
		[ $ago -eq 0 ] && ago=1
		[ 300 -gt $ago ] && PKG_UPGRADING=$ago && return 0

		return 1
	done

	# We shouldn't be here
	return 1
}

#############################################################
## Dummy logcode
#############################################################
Log() 
{
	return
}

######################################
## Find the IP address of the box
FrameworkGetIPAddress()
{
	# Detect interfaces
	local interfaces=` ifconfig | grep -e "^egiga" -e "^bond" -e "^eth" | cut -d ' ' -f 1 `

	# And find the IP (v4) address
	for interface in $interfaces
	do
		local address=` ifconfig ${interface} | grep "inet addr" | tr -s ' ' `
		if [ "${address}" != "" ] ; then
			echo ${address} | cut -d ' ' -f 2 | cut -d ':' -f 2
			return
		fi
	done
	hostname # What else?
}

#####################################
## Echo the URL of the package
FrameworkGetLink()
{
	# Do we have a webinterface at all?
	[ ! -d ${PKG_ROOT}/gui/${PKG_NAME}/ ] && exit 0

	local address=` FrameworkGetIPAddress `

	# Seach for configured ports
	local ports=
	for directory in /etc/pkg_service_conf /etc/service_conf
	do
		[ ! -d ${directory} ] && continue

		ports=` grep "^Listen" ${directory}/httpd_zld*.conf | awk '{ print $2 }' `
		ports="$ports ` grep "^<VirtualHost" ${directory}/httpd_zld*.conf | cut -d ':' -f 2 | cut -d '>' -f 1 `"
		ports=` echo $ports | tr -s ' ' | tr ' ' '\n' | sort | uniq | grep -v 8082 `
		break
	done

	for port in $ports
	do
		# Find out if it's https:
		protocol=http
		defaultport=80
		grep -i "^<VirtualHost.*${port}" -A 50 ${directory}/httpd_zld*.conf >/tmp/.$$.${PKG_NAME}

		while read line
		do
			if echo $line | grep -i "^</VirtualHost" >/dev/null
			then
				break
			fi

			if echo $line | grep -i "SSLEngine *On" >/dev/null
			then
				protocol=https
				defaultport=443
			fi
		done </tmp/.$$.${PKG_NAME}
		rm /tmp/.$$.${PKG_NAME}

		[ ${defaultport} -eq 443 ] && continue # Package manager crashes on https :$


		[ $port -eq $defaultport ] && port="" || port=":${port}"

		local url="${protocol}://${address}${port}/pkg/${PKG_NAME}/"

		echo  $url
		# We can only output a single url
		return
	done
}

######################################
## Status get and set
FrameworkStatus()
{
	local pkg_config_file="${PKG_ROOT}/config/${PKG_NAME}/config"
	if [ "get" = "$1" ] ; then
		if [ ! -f ${pkg_config_file} ] ; then
			FrameworkStatus set Disabled
		fi
		cat ${pkg_config_file}
		return
	elif [ "set" = "$1" ] ; then
		mkdir -p ` dirname ${pkg_config_file} `
		
		echo $2 >${pkg_config_file}
	fi
}

################################################
## Run or stop the package
FrameworkRun()
{
	if [ $1 -eq 1 ] ; then
		# Startup
		STATUS=` FrameworkStatus get `
		[ "$STATUS" != "Enabled" ] && return	# We're not enabled

		# Do we have a webinterface?
		if [ -d ${PKG_ROOT}/gui/${PKG_NAME}/ ] ; then
			# Aparently 
			for httpdconf in /etc/pkg_service_conf/httpd_package2.conf
			do
				[ ! -f ${httpdconf} ] && continue
				
				local service_conf=` dirname $httpdconf `

				echo Alias /pkg/${PKG_NAME}/ ${PKG_ROOT}/gui/${PKG_NAME}/ >${service_conf}/${PKG_NAME}.conf
				if ! grep ${PKG_NAME}.conf ${httpdconf} >/dev/null
				then
					sed -i "1iInclude ${service_conf}/${PKG_NAME}.conf" ${httpdconf}
				fi

				# Let the package manager restart the server
				touch /tmp/restart_httpd
				break
			done

		fi

		[ ! -f /lib/ld-linux.so.3 -a -f /lib/ld-linux-armhf.so.3 ] && ln -s ld-linux-armhf.so.3 /lib/ld-linux.so.3 

		Startup
		return
	fi

	Shutdown
	
	for httpdconf in /etc/pkg_service_conf/httpd_package2.conf
	do
		[ ! -f ${httpdconf} ] && continue
		grep -v ${PKG_NAME}.conf ${httpdconf} >/tmp/$$.httpd.conf
		mv /tmp/$$.httpd.conf ${httpdconf}
		touch /tmp/restart_httpd
	break
	done

}

FrameworkVersion()
{
	local controlfile=${PKG_ROOT}/zypkg_conf/info/${PKG_NAME}.control
	local version=$( grep "^Version:" ${controlfile} | awk -F"zypkg" '{print $2}' )
	exit $version
}

FrameworkParseParams()
{
	case $1 in
		getlink)
			FrameworkGetLink
			;;
		status)
			FrameworkStatus get
			;;
		enable)
			FrameworkStatus set Enabled 
			FrameworkRun 1 </dev/null
			;;
		disable)
			FrameworkRun 0 </dev/null
			FrameworkStatus set Disabled 
			;;
		startup)
			FrameworkRun 1 </dev/null
			;;
		shutdown)
			FrameworkRun 0 </dev/null
			;;
		version)
			FrameworkVersion
			;;
	esac
}

Log

PKG_ROOT="/usr/local/zy-pkgs"
PKG_MEDION=0

PKG_MEDION=0
WEB_PREFIX=/i-data/md0/admin/zy-pkgs/web_prefix
MEDION_PREFIX=/etc/package_src_url
INITD=${PKG_ROOT}/etc/init.d/

MedionPatchStop()
{
	Log MedionPatchStop
        for file in ` ls ${INITD}patched/ `
        do
                mv ${INITD}patched/${file} ${INITD}
        done
        rmdir ${INITD}patched/
}

MedionPatchStart()
{
	chmod a+x $0 # Maybe some cgiscript wants to talk to it's startscript
	
        for file in ` ls ${INITD} `
        do
		[ -d ${INITD}${file} ] && continue
		[ -h ${INITD}${file} ] && continue
		[ ! -x ${INITD}${file} ] && continue
		[ "${file}" = "${PKG_NAME}" ] && continue
		[ "${file}" = "ZYPKG_DEPS" ] && continue
                mkdir -p ${INITD}patched/
                mv ${INITD}${file} ${INITD}patched/
                ln -s ${INITD}${PKG_NAME} ${INITD}${file}
        done
}

MedionPatchApply()
{
	local file=` basename $1 `
	[ ! -x ${INITD}patched/${file} ] && exit 1
	shift
	
	local result=` ${INITD}patched/${file} "$@" `
	local ret=$?
	
	[ $ret -ne 0 ] && exit $ret
	
	[ "$1" != "getlink" ] && echo $result && exit 0
	
	[ -f /etc/service_conf/${file}.conf ] && echo $result && exit 0
	
		# if this is a patchable link, the 4rd element is pkg
	local fourth=` echo $result | cut -d '/' -f '4' `
	[ "$fourth" != "pkg" ] && echo $result && exit 0
	
	local revision=` grep RewriteRule /etc/service_conf/httpd_zld.conf | grep playzone | cut -d '/' -f 3 `
	[ "${revision}" = "" ] && echo $result && exit 0
	
	echo $result | sed sX/pkg/X/${revision}/adv\,/pkg/X
	exit 0
}

StartServer()
{
	local pkg_root=$1
	local medion_patch=$2

	local config=${pkg_root}/etc/${PKG_NAME}.conf
	. ${config}

	local servicedir=/tmp/.${PKG_NAME}/etc/
	local bindir=/tmp/.${PKG_NAME}/bin/
	local tmpdir=/tmp/.${PKG_NAME}/tmp/
	mkdir -p $servicedir
	mkdir -p $bindir
	mkdir -p $tmpdir
	mkdir -p ${SCRATCH}
	chmod a+w ${SCRATCH}
	chmod a+w ${config}
	chmod a+w ${tmpdir}

	[ ! -f /lib/ld-linux.so.3 -a -f /lib/ld-linux-armhf.so.3 ] && ln -s ld-linux-armhf.so.3 /lib/ld-linux.so.3 
	ln -s ${pkg_root}/bin/tar ${bindir}tar
	ln -s ${pkg_root}/bin/busybox-metarepo ${bindir}busybox-metarepo

	echo "${LISTEN_AT}	stream	tcp	nowait	nobody	${pkg_root}/gui/${PKG_NAME}/pkgcgi.cgi	pkgcgi.cgi inetd-server" >${servicedir}inetd.conf

	${bindir}/busybox-metarepo inetd ${servicedir}inetd.conf
	
	if [ ${PKG_MEDION} -eq 1 ] ; then
		[ ! -f ${MEDION_PREFIX}.${PKG_NAME} ] && mv ${MEDION_PREFIX} ${MEDION_PREFIX}.${PKG_NAME}
		echo "http://localhost:${LISTEN_AT}/package" >${MEDION_PREFIX}
		[ $medion_patch -eq 1 ] && MedionPatchStart
	else
		echo "http://localhost:${LISTEN_AT}/" >${WEB_PREFIX}
	fi
}

StopServer()
{
	killall busybox-metarepo
	local bindir=/tmp/.${PKG_NAME}/bin
	rm ${bindir}/tar
	rm ${bindir}/busybox-metarepo
	rmdir ${bindir}
}

Startup()
{
	StartServer ${PKG_ROOT} 1
}

Shutdown()
{
	StopServer

	if [ -f ${MEDION_PREFIX}.${PKG_NAME} ] ; then
		[ -f ${MEDION_PREFIX} ] && rm ${MEDION_PREFIX}
		mv ${MEDION_URL}.${PKG_NAME} ${MEDION_PREFIX}
		MedionPatchStop
	else
		rm ${WEB_PREFIX}
	fi
}

PostDisable()
{
	IsUpgrading
	if [ $? -ne 0 ] ; then
		return 0
	fi
	
	Log "Upgrading. Will copy stuff to a safe place"
	
	local tmproot=/tmp/.${PKG_NAME}/
	mkdir -p ${tmproot}gui/${PKG_NAME}/
	cp -a ${PKG_ROOT}/gui/${PKG_NAME}/* ${tmproot}gui/${PKG_NAME}/
	sed -i "s|/usr/local/zy-pkgs/|${tmproot}|g" ${tmproot}gui/${PKG_NAME}/*
	mkdir -p ${tmproot}etc/
	cp -a ${PKG_ROOT}/etc/${PKG_NAME}* ${tmproot}etc/
	mkdir -p ${tmproot}bin/
	cp -a ${PKG_ROOT}/bin/busybox-metarepo ${tmproot}bin/

	Log "Start temporary server"
	StartServer $tmproot 0
}

PreEnable()
{
	# New version upgrade
	tmproot=/tmp/.${PKG_NAME}/
	if [ -d $tmproot -a -f ${tmproot}bin/busybox-metarepo ] ; then
		Log "Detected an old installation. Copy configuration"
		cp ${tmproot}etc/${PKG_NAME}.conf ${PKG_ROOT}/etc/
		# Stop 'update server'
		Log "Stop 'new style' server"
		StopServer
		sleep 5 # Make sure it's stopped
		rm -rf ${tmproot}
	fi
}

[ ${PKG_MEDION} -eq 1 -a "` basename $0 `" != "${PKG_NAME}" ] && MedionPatchApply $0 "$@"

case $1 in
	enable)
		PreEnable
		;;
	disable)
		FrameworkParseParams "$@"
		PostDisable
		exit 0
		;;
	getlink)
		if [ ${PKG_MEDION} -ne 0 ] ; then
			local address=` FrameworkGetIPAddress `
			local revision=` grep RewriteRule /etc/service_conf/httpd_zld.conf | grep playzone | cut -d '/' -f 3 `

			echo  "http://${address}/${revision}/adv,/pkg/${PKG_NAME}/"
			MedionPatchStart
			exit 0
		fi
		;;
esac

FrameworkParseParams "$@"

exit 0
