#!/bin/sh
# ============================================================================
#
# This file is part of the 'GenerateZypkgFramework' 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>
#
# ============================================================================

StripEmbedded()
{
	while IFS='' read -r line
	do
		echo "${line:13}"
#		echo $line | cut -s -d ' ' -f 2-
	done
}

AddPreserveDownloadUrl()
{
	[ "${PRESERVE_DOWNLOAD_URL}" = "" ] && return 0
	
	echo PKG_DOWNLOAD_URL=${PRESERVE_DOWNLOAD_URL}
}

AddIsUpgrading()
{
	StripEmbedded <<__EOF__
EmbeddedCode ############################################################
EmbeddedCode ## Check if we are in upgradig mode. From the point of view of the package
EmbeddedCode ## an upgrade is a uninstall followed by a install. So if you want to preserve
EmbeddedCode ## something over an upgrade, you have to detect it somehow
EmbeddedCode ##
EmbeddedCode ## Function sets PKG_UPGRADE > 0 when upgrading, 
EmbeddedCode ## and PKG_UPGRADE=0 when not
EmbeddedCode ############################################################
EmbeddedCode IsUpgrading()
EmbeddedCode {
EmbeddedCode 	PKG_UPGRADING=0
EmbeddedCode 	local dir=
EmbeddedCode 	for dir in "/usr/local/zy-pkgs/" "/i-data/.system/zy-pkgs/"
EmbeddedCode 	do
EmbeddedCode 		local logfile=\${dir}tmp/zypkg.log
EmbeddedCode 		[ ! -f \${logfile} ] && continue
EmbeddedCode 
EmbeddedCode 		local lastupdate=\` grep "Upgrade Mode" \${logfile} | tail -n 1 | grep "\[\${PKG_NAME}\]" | awk -v OFS=' ' '{print \$1, \$2}' \`
EmbeddedCode 
EmbeddedCode 	        [ "\${lastupdate}" = "" ] && return 1
EmbeddedCode 
EmbeddedCode 		local since1970=\` TZ=GMT date -d "\${lastupdate}" +%s \`
EmbeddedCode 		local now=\`date +%s \`
EmbeddedCode 		local ago=""
EmbeddedCode 		let ago=now-since1970
EmbeddedCode 		[ \$ago -eq 0 ] && ago=1
EmbeddedCode 		[ 300 -gt \$ago ] && PKG_UPGRADING=\$ago && return 0
EmbeddedCode 
EmbeddedCode 		return 1
EmbeddedCode 	done
EmbeddedCode 
EmbeddedCode 	# We shouldn't be here
EmbeddedCode 	return 1
EmbeddedCode }
EmbeddedCode 
__EOF__
}

AddLoggingCode()
{
	if [ 0 -eq ${ENABLE_LOGFILE} ] ; then
		StripEmbedded <<__EOF__
EmbeddedCode #############################################################
EmbeddedCode ## Dummy logcode
EmbeddedCode #############################################################
EmbeddedCode Log() 
EmbeddedCode {
EmbeddedCode 	return
EmbeddedCode }
EmbeddedCode 
__EOF__
		return
	fi	
	
	
	if [ 1 -eq ${ENABLE_LOGFILE} ] ; then
		StripEmbedded <<__EOF__
EmbeddedCode #############################################################
EmbeddedCode ## Write some useful log to /tmp/${PKG_NAME}.log. -if it exists
EmbeddedCode #############################################################
EmbeddedCode Log() 
EmbeddedCode {
EmbeddedCode 	[ ! -f /tmp/\${PKG_NAME}.log ] && return
EmbeddedCode 	echo "\` date \` \${THIS_FILE}: \$0 \$@" >>/tmp/\${PKG_NAME}
EmbeddedCode }
EmbeddedCode 
__EOF__
	    return
	fi	

	if [ 3 -eq ${ENABLE_LOGFILE} ] ; then
		local log="/tmp/\${PKG_NAME}.log"
		local stderr="/tmp/\${PKG_NAME}.stderr.\$$.log"
		local stdout="/tmp/\${PKG_NAME}.stdout.\$$.log"
		
		StripEmbedded <<__EOF__
EmbeddedCode #############################################################
EmbeddedCode ## Redirect stdout & err, write to log
EmbeddedCode #############################################################
EmbeddedCode FrameworkLogStdoutErr()
EmbeddedCode {
EmbeddedCode    local ret=\$?
EmbeddedCode 	exec 1>&5
EmbeddedCode 	exec 5>&-
EmbeddedCode 	echo -e "\tstdout" >>${log}
EmbeddedCode 	cat ${stdout} >>${log}
EmbeddedCode 	cat ${stdout} >&1
EmbeddedCode 	rm ${stdout}
EmbeddedCode 	exec 2>&6
EmbeddedCode 	exec 6>&-
EmbeddedCode 	echo -e "\tstderr" >>${log}
EmbeddedCode 	cat ${stderr} >>${log}
EmbeddedCode 	cat ${stderr} >&2
EmbeddedCode 	rm ${stderr}
EmbeddedCode	echo -e "\texit \$ret" >>${log}
EmbeddedCode 	exit \$ret
EmbeddedCode }
EmbeddedCode 
EmbeddedCode if [ -f ${log} ] ; then
EmbeddedCode 	exec 5>&1
EmbeddedCode 	exec 1>${stdout}
EmbeddedCode 	exec 6>&2
EmbeddedCode 	exec 2>${stderr}
EmbeddedCode 	trap FrameworkLogStdoutErr EXIT
EmbeddedCode fi
EmbeddedCode 
__EOF__
	fi
	
	StripEmbedded <<__EOF__ 
EmbeddedCode #############################################################
EmbeddedCode ## Internal function of Log. Find parent, and print cmdline of process $1
EmbeddedCode #############################################################
EmbeddedCode FindParent()
EmbeddedCode {
EmbeddedCode 	local id=\${1}
EmbeddedCode 	[ \$id -eq 1 ] && return # process 1 is the root of all processes
EmbeddedCode 
EmbeddedCode 	local ppid=\` grep PPid /proc/\$id/status | awk '{ print \$2 }' \`
EmbeddedCode 	FindParent \$ppid
EmbeddedCode 
EmbeddedCode 	local cmdline=\` cat /proc/\$id/cmdline | tr '\0' ' ' \`
EmbeddedCode 	echo \${id}\${INDENT}\${cmdline}
EmbeddedCode 	INDENT="\${INDENT}*"
EmbeddedCode }
EmbeddedCode 
EmbeddedCode #############################################################
EmbeddedCode ## Write some useful log to /tmp/${PKG_NAME}.log. -if it exists
EmbeddedCode #############################################################
EmbeddedCode Log() 
EmbeddedCode {
EmbeddedCode 	[ ! -f /tmp/\${PKG_NAME}.log ] && return
EmbeddedCode 
EmbeddedCode 	if [ "\$1" = "bare" ] ; then
EmbeddedCode  		shift
EmbeddedCode 		echo "\${THIS_SCRIPT}: \$@" >>/tmp/\${PKG_NAME}.log
EmbeddedCode 		return
EmbeddedCode 	fi
EmbeddedCode 
EmbeddedCode 	exec 3>&1 ; exec 4>&2 ; exec >>/tmp/\${PKG_NAME}.log 2>/dev/null
EmbeddedCode 	echo "#######################################"
EmbeddedCode 	echo "## Script: \${THIS_SCRIPT}"
EmbeddedCode 	echo "#######################################"
EmbeddedCode 	echo -e "\tTime: \` date +%T \`"
EmbeddedCode 	[ "\$1" != "" ] && echo -e "\tMessage: \$@"
EmbeddedCode 	echo -e "\tCall stack"
EmbeddedCode 	INDENT="*"
EmbeddedCode 	local tmpfile=/tmp/\$\$.\${PKG_NAME}
EmbeddedCode 	FindParent \$\$ >\$tmpfile
EmbeddedCode 	unset INDENT
EmbeddedCode 	local line
EmbeddedCode 	while read line
EmbeddedCode 	do
EmbeddedCode 	    echo -e "\t\t\${line}" | tr '*' '\t'
EmbeddedCode 	done <\$tmpfile
EmbeddedCode 	rm \$tmpfile
EmbeddedCode 	echo -e "\tCurdir: \` pwd \`"
EmbeddedCode 	[ -h \$0 ] && echo -e "\tSymlink: \$0 is a symlink to \` readlink \$0 \`"
EmbeddedCode 	echo -e "\tEnvironment"
EmbeddedCode 	printenv >\$tmpfile
EmbeddedCode 	while read line 
EmbeddedCode 	do
EmbeddedCode 	    echo -e "\t\t\${line}"
EmbeddedCode 	done <\$tmpfile
EmbeddedCode 	rm \$tmpfile
EmbeddedCode 	exec 2>&4 ; exec 4>&- ; exec 1>&3 ; exec 3>&-
EmbeddedCode }
EmbeddedCode 
__EOF__
} ## AddLoggingCode

AddStartScript()
{
	local startup=0
	local shutdown=0
	local getlink=0

	if [ -f ${CURDIR}/startscript ] ; then
		if grep "^Startup()" ${CURDIR}/startscript >/dev/null 2>&1
		then
			startup=1
		fi
		
		if grep "^Shutdown()" ${CURDIR}/startscript >/dev/null 2>&1
		then
			shutdown=1
		fi

		if grep "^GetLink()" ${CURDIR}/startscript >/dev/null 2>&1
		then
			getlink=1
		fi

	fi

	StripEmbedded <<__EOF__
EmbeddedCode ######################################
EmbeddedCode ## Find the IP address of the box
EmbeddedCode FrameworkGetIPAddress()
EmbeddedCode {
EmbeddedCode 	# Detect interfaces
EmbeddedCode 	local interfaces=\` ifconfig | grep -e "^egiga" -e "^bond" -e "^eth" | cut -d ' ' -f 1 \`
EmbeddedCode 
EmbeddedCode 	# And find the IP (v4) address
EmbeddedCode 	for interface in \$interfaces
EmbeddedCode 	do
EmbeddedCode 		local address=\` ifconfig \${interface} | grep "inet addr" | tr -s ' ' \`
EmbeddedCode 		if [ "\${address}" != "" ] ; then
EmbeddedCode 			echo \${address} | cut -d ' ' -f 2 | cut -d ':' -f 2
EmbeddedCode 			return
EmbeddedCode 		fi
EmbeddedCode 	done
EmbeddedCode 	hostname # What else?
EmbeddedCode }
EmbeddedCode 
__EOF__

	
	local customalias=0

	if [ -z ${ENABLE_WEBINTERFACE} -o "${ENABLE_WEBINTERFACE}" != "1" ] ; then
		ENABLE_WEBINTERFACE=0
		ENABLE_LOGINLESS=0
		if [ $getlink -eq 1 ] ; then
			StripEmbedded <<__EOF__
EmbeddedCode #####################################
EmbeddedCode ## Echo the URL of the package
EmbeddedCode FrameworkGetLink()
EmbeddedCode {
EmbeddedCode 	GetLink
EmbeddedCode }
EmbeddedCode 
__EOF__
		else
			StripEmbedded <<__EOF__
EmbeddedCode #####################################
EmbeddedCode ## Echo the URL of the package
EmbeddedCode FrameworkGetLink()
EmbeddedCode {
EmbeddedCode 	return
EmbeddedCode }
EmbeddedCode 
__EOF__
		fi
	else # ENABLE_WEBINTERFACE
	
		if [ -z ${CUSTOM_WEBINTERFACE} ] ; then
		    CUSTOM_WEBINTERFACE="\${PKG_ROOT}/gui/\${PKG_NAME}/"
		else
		    if [ "${CUSTOM_WEBINTERFACE:1:1}" != "/" ] ; then
			# not relative
			[ "` dirname ${CUSTOM_WEBINTERFACE} `" != "pkg" ] && customalias=1
			CUSTOM_WEBINTERFACE="\${PKG_ROOT}/${CUSTOM_WEBINTERFACE}"
		    else
			customalias=1
		    fi
		fi
		if [ -z ${CUSTOM_WEBALIAS} ] ; then
		    CUSTOM_WEBALIAS="/pkg/\${PKG_NAME}/"
		else
		    [ "` dirname ${CUSTOM_WEBALIAS} `" != '/pkg' ] && customalias=1
		fi
		# If customalias = 1, then we have to patch httpd.conf on fw < 5
		
		if [ -z ${ENABLE_LOGINLESS} -o ${ENABLE_LOGINLESS} -ne 1 ] ; then
			ENABLE_LOGINLESS=0
		else
			StripEmbedded <<__EOF__
EmbeddedCode ###################################
EmbeddedCode ## Adds the pattern of the package to AuthZyxelSkipPattern in httpd.conf
EmbeddedCode ## to suppress login need
EmbeddedCode ## 1st argimant [0|1] disable/enable
EmbeddedCode ## 2nd argument path to conffile
EmbeddedCode FrameworkEnableLoginlessPattern()
EmbeddedCode {
EmbeddedCode 	local enable=\$1
EmbeddedCode 	local httpdconf=\$2
EmbeddedCode 	local name=AuthZyxelSkipPattern
EmbeddedCode 
EmbeddedCode 	if grep \$name \$httpdconf | grep "${CUSTOM_WEBALIAS}" >/dev/null 
EmbeddedCode 	then
EmbeddedCode 		if [ \$enable -eq 1 ] ; then
EmbeddedCode 			# nothing to do
EmbeddedCode 			return
EmbeddedCode 		else
EmbeddedCode 			sed -i "s|${CUSTOM_WEBALIAS}||" \$httpdconf
EmbeddedCode 		fi
EmbeddedCode 	else
EmbeddedCode 		if [ \$enable -eq 1 ] ; then
EmbeddedCode 			sed -i "s|\${name} |\${name} ${CUSTOM_WEBALIAS} |" \$httpdconf
EmbeddedCode 		else
EmbeddedCode 			# nothing to do
EmbeddedCode 			return 
EmbeddedCode 		fi
EmbeddedCode 	fi
EmbeddedCode 
EmbeddedCode 	# let the firmware restart the server
EmbeddedCode 	touch /tmp/restart_httpd
EmbeddedCode }
EmbeddedCode 
__EOF__
		fi # ENABLE_LOGINLESS
		

	StripEmbedded <<__EOF__
EmbeddedCode #####################################
EmbeddedCode ## Echo the URL of the package
EmbeddedCode FrameworkGetLink()
EmbeddedCode {
EmbeddedCode 	# Do we have a webinterface at all?
EmbeddedCode 	[ ! -d ${CUSTOM_WEBINTERFACE} ] && exit 0
EmbeddedCode 
EmbeddedCode 	local address=\` FrameworkGetIPAddress \`
EmbeddedCode 
EmbeddedCode 	# Seach for configured ports
EmbeddedCode 	local ports=
EmbeddedCode 	for directory in /etc/pkg_service_conf /etc/service_conf
EmbeddedCode 	do
EmbeddedCode 		[ ! -d \${directory} ] && continue
EmbeddedCode 
EmbeddedCode 		ports=\` grep "^Listen" \${directory}/httpd_zld*.conf | awk '{ print \$2 }' \`
EmbeddedCode 		ports="\$ports \` grep "^<VirtualHost" \${directory}/httpd_zld*.conf | cut -d ':' -f 2 | cut -d '>' -f 1 \`"
EmbeddedCode 		ports=\` echo \$ports | tr -s ' ' | tr ' ' '\n' | sort | uniq | grep -v 8082 \`
EmbeddedCode 		break
EmbeddedCode 	done
EmbeddedCode 
EmbeddedCode 	for port in \$ports
EmbeddedCode 	do
EmbeddedCode 		# Find out if it's https:
EmbeddedCode 		protocol=http
EmbeddedCode 		defaultport=80
EmbeddedCode 		grep -i "^<VirtualHost.*\${port}" -A 50 \${directory}/httpd_zld*.conf >/tmp/.\$\$.\${PKG_NAME}
EmbeddedCode 
EmbeddedCode 		while read line
EmbeddedCode 		do
EmbeddedCode 			if echo \$line | grep -i "^</VirtualHost" >/dev/null
EmbeddedCode 			then
EmbeddedCode 				break
EmbeddedCode 			fi
EmbeddedCode 
EmbeddedCode 			if echo \$line | grep -i "SSLEngine *On" >/dev/null
EmbeddedCode 			then
EmbeddedCode 				protocol=https
EmbeddedCode 				defaultport=443
EmbeddedCode 			fi
EmbeddedCode 		done </tmp/.\$\$.\${PKG_NAME}
EmbeddedCode 		rm /tmp/.\$\$.\${PKG_NAME}
EmbeddedCode 
EmbeddedCode 		[ \${defaultport} -eq 443 ] && continue # Package manager crashes on https :$
EmbeddedCode 
EmbeddedCode 
EmbeddedCode 		[ \$port -eq \$defaultport ] && port="" || port=":\${port}"
EmbeddedCode
EmbeddedCode 		local url="\${protocol}://\${address}\${port}${CUSTOM_WEBALIAS}"
EmbeededCode 
EmbeddedCode 		echo  \$url
EmbeddedCode 		# We can only output a single url
EmbeddedCode 		return
EmbeddedCode 	done
EmbeddedCode }
EmbeddedCode 
__EOF__
	fi # ENABLE_WEBINTERFACE

	StripEmbedded <<__EOF__	
EmbeddedCode ######################################
EmbeddedCode ## Status get and set
EmbeddedCode FrameworkStatus()
EmbeddedCode {
EmbeddedCode 	local pkg_config_file="\${PKG_ROOT}/config/\${PKG_NAME}/config"
EmbeddedCode 	if [ "get" = "\$1" ] ; then
EmbeddedCode 		if [ ! -f \${pkg_config_file} ] ; then
EmbeddedCode 			FrameworkStatus set Disabled
EmbeddedCode 		fi
EmbeddedCode 		cat \${pkg_config_file}
EmbeddedCode 		return
EmbeddedCode 	elif [ "set" = "\$1" ] ; then
EmbeddedCode 		mkdir -p \` dirname \${pkg_config_file} \`
EmbeddedCode 		
EmbeddedCode 		echo \$2 >\${pkg_config_file}
EmbeddedCode 	fi
EmbeddedCode }
EmbeddedCode 
EmbeddedCode ################################################
EmbeddedCode ## Run or stop the package
EmbeddedCode FrameworkRun()
EmbeddedCode {
EmbeddedCode 	if [ \$1 -eq 1 ] ; then
EmbeddedCode 		# Startup
EmbeddedCode 		STATUS=\` FrameworkStatus get \`
EmbeddedCode 		[ "\$STATUS" != "Enabled" ] && return	# We're not enabled
EmbeddedCode 
__EOF__
	
	local httpdconflist=/etc/pkg_service_conf/httpd_package2.conf
	[ 1 -eq ${customalias} ] && httpdconflist="/etc/pkg_service_conf/httpd_package2.conf /etc/service_conf/httpd_package.conf"

	if [ ${ENABLE_WEBINTERFACE} -eq 1 ] ; then
		StripEmbedded <<__EOF__
EmbeddedCode 		# Do we have a webinterface?
EmbeddedCode 		if [ -d ${CUSTOM_WEBINTERFACE} ] ; then
EmbeddedCode 			# Aparently 
EmbeddedCode 			for httpdconf in ${httpdconflist}
EmbeddedCode 			do
EmbeddedCode 				[ ! -f \${httpdconf} ] && continue
EmbeddedCode 				
EmbeddedCode 				local service_conf=\` dirname \$httpdconf \`
EmbeddedCode
EmbeddedCode 				echo Alias ${CUSTOM_WEBALIAS} ${CUSTOM_WEBINTERFACE} >\${service_conf}/\${PKG_NAME}.conf
EmbeddedCode 				if ! grep \${PKG_NAME}.conf \${httpdconf} >/dev/null
EmbeddedCode 				then
EmbeddedCode 					sed -i "1iInclude \${service_conf}/\${PKG_NAME}.conf" \${httpdconf}
EmbeddedCode 				fi
EmbeddedCode 
EmbeddedCode 				# Let the package manager restart the server
EmbeddedCode 				touch /tmp/restart_httpd
EmbeddedCode 				break
EmbeddedCode 			done
EmbeddedCode 
__EOF__
		if [ ${ENABLE_LOGINLESS} -eq 1 ] ; then
			StripEmbedded <<__EOF__
EmbeddedCode 			# Enable loginless access
EmbeddedCode 			for httpdconf in /etc/pkg_service_conf/httpd2.conf /etc/service_conf/httpd.conf
EmbeddedCode 			do
EmbeddedCode 				[ ! -f \${httpdconf} ] && continue
EmbeddedCode 				FrameworkEnableLoginlessPattern 1 \${httpdconf} 
EmbeddedCode 				break
EmbeddedCode 			done
__EOF__
		fi # ENABLE_LOGINLESS
		
		StripEmbedded <<__EOF__
EmbeddedCode 		fi
Embeddedcode 
Embeddedcode 		[ ! -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 
Embeddedcode 
__EOF__
	fi # ENABLE_WEBINTERFACE

	[ $startup -eq 1 ] && StripEmbedded <<__EOF__
EmbeddedCode 		Startup
__EOF__
	
	StripEmbedded <<__EOF__
EmbeddedCode 		return
EmbeddedCode 	fi
EmbeddedCode 
__EOF__

	[ $shutdown -eq 1 ] && StripEmbedded <<__EOF__
EmbeddedCode 	Shutdown
EmbeddedCode 	
__EOF__

	if [ ${ENABLE_WEBINTERFACE} -eq 1 ] ; then
		StripEmbedded <<__EOF__
EmbeddedCode 	for httpdconf in ${httpdconflist}
EmbeddedCode 	do
EmbeddedCode 		[ ! -f \${httpdconf} ] && continue
EmbeddedCode 		grep -v \${PKG_NAME}.conf \${httpdconf} >/tmp/\$\$.httpd.conf
EmbeddedCode 		mv /tmp/\$\$.httpd.conf \${httpdconf}
EmbeddedCode 		touch /tmp/restart_httpd
EmbeddedCode		break
EmbeddedCode 	done
EmbeddedCode 
__EOF__
		if [ ${ENABLE_LOGINLESS} -eq 1 ] ; then
			StripEmbedded <<__EOF__
EmbeddedCode 	# Disable loginless access
EmbeddedCode 	for httpdconf in /etc/pkg_service_conf/httpd2.conf /etc/service_conf/httpd.conf
EmbeddedCode 	do
EmbeddedCode 		[ ! -f \${httpdconf} ] && continue
EmbeddedCode 		EnableLoginlessPattern 0 \${httpdconf} 
EmbeddedCode 		break
EmbeddedCode 	done
__EOF__
		fi # ENABLE_LOGINLESS
	fi # ENABLE_WEBINTERFACE


CONTROLFILE="/i-data/38aa86ff/.PKG/NZBGet/zypkg_conf/info/${PKG_NAME}.control"

	
	StripEmbedded <<__EOF__
EmbeddedCode }
EmbeddedCode 
EmbeddedCode FrameworkVersion()
EmbeddedCode {
EmbeddedCode 	local controlfile=\${PKG_ROOT}/zypkg_conf/info/\${PKG_NAME}.control
EmbeddedCode 	local version=\$( grep "^Version:" \${controlfile} | awk -F"zypkg" '{print \$2}' )
EmbeddedCode 	exit \$version
EmbeddedCode }
EmbeddedCode 
EmbeddedCode FrameworkParseParams()
EmbeddedCode {
EmbeddedCode 	case \$1 in
EmbeddedCode 		getlink)
EmbeddedCode 			FrameworkGetLink
EmbeddedCode 			;;
EmbeddedCode 		status)
EmbeddedCode 			FrameworkStatus get
EmbeddedCode 			;;
EmbeddedCode 		enable)
EmbeddedCode 			FrameworkStatus set Enabled 
EmbeddedCode 			FrameworkRun 1 </dev/null
EmbeddedCode 			;;
EmbeddedCode 		disable)
EmbeddedCode 			FrameworkRun 0 </dev/null
EmbeddedCode 			FrameworkStatus set Disabled 
EmbeddedCode 			;;
EmbeddedCode 		startup)
EmbeddedCode 			FrameworkRun 1 </dev/null
EmbeddedCode 			;;
EmbeddedCode 		shutdown)
EmbeddedCode 			FrameworkRun 0 </dev/null
EmbeddedCode 			;;
EmbeddedCode 		version)
EmbeddedCode 			FrameworkVersion
EmbeddedCode 			;;
EmbeddedCode 	esac
EmbeddedCode }
EmbeddedCode 
EmbeddedCode Log
EmbeddedCode 
EmbeddedCode PKG_ROOT="/usr/local/zy-pkgs"
__EOF__
	if [ ${CHECK_FOR_MEDION} -eq 1 ] ; then
		StripEmbedded <<__EOF__
EmbeddedCode PKG_MEDION=0
__EOF__
	fi
	echo

	[ -f ${CURDIR}/startscript ] && cat ${CURDIR}/startscript

	StripEmbedded <<__EOF__
EmbeddedCode FrameworkParseParams "\$@"
EmbeddedCode 
EmbeddedCode exit 0
__EOF__

}  ## End AddStartScript


GenerateEmptyProject()
{
	echo Generating ${PACKAGENAME} in ${TARGETDIR}

	local rootdir=${TARGETDIR}/${PACKAGENAME}
	mkdir -p ${rootdir}
	[ $? -ne 0 ] && echo FATAL. Cannot create ${rootdir} && exit 1

	# Startscript, Copy header of this file, and add stuff
	local startscript=${rootdir}/data/etc/init.d/${PACKAGENAME}
	echo ${startscript}...
	mkdir -p ` dirname $startscript `
	exec 3>&1 ; exec 1>${startscript} # stdout to startscript

	while IFS= read -r line
	do
		if echo $line | grep "^#" >/dev/null
		then
			echo "$line" | sed "s|${BASENAME}|${PACKAGENAME}|"
		else
			break
		fi
	done < $0

	StripEmbedded <<__EOF__
EmbeddedCode PKG_NAME="${PACKAGENAME}"
EmbeddedCode THIS_SCRIPT="${PACKAGENAME}"
EmbeddedCode PKG_FIRMWARE=4
EmbeddedCode 
__EOF__
	AddPreserveDownloadUrl
	AddIsUpgrading
	AddLoggingCode
	AddStartScript

	exec 1>&3 ; exec 3>&- # stdout to stdout

	chmod 755 $startscript

	# Controlscripts
	local control=${rootdir}/control
	mkdir -p ${control}

	for script in preinst ReplaceRule postinst prerm postrm
	do
		local controlscript=${control}/${script}
		echo ${controlscript}...
		exec 3>&1 ; exec 1>${controlscript}

		while IFS= read -r line
		do
			if echo $line | grep "^#" >/dev/null
			then
				echo "$line" | sed "s|${BASENAME}|${PACKAGENAME}|"
			else
				break
			fi
		done < $0

		StripEmbedded <<__EOF__
EmbeddedCode PKG_NAME="${PACKAGENAME}"
EmbeddedCode THIS_SCRIPT="${script}"
EmbeddedCode PKG_VERSION="${PKG_VERSION}zypkg${PKG_REVISION}"
__EOF__

		if [ "${script}" = "ReplaceRule" ] ; then
			StripEmbedded <<__EOF__
EmbeddedCode 
EmbeddedCode #############################################################
EmbeddedCode ## Extract the PKG_ROOT for this package
EmbeddedCode ##
EmbeddedCode ## Function sets PKG_ROOT (without trainling slash)
EmbeddedCode #############################################################
EmbeddedCode GetPkgRoot()
EmbeddedCode {
EmbeddedCode 	if [ -d /zyxel/mnt/info ]
EmbeddedCode 	then
EmbeddedCode 		# No firmware 5.x (then it's /firmware/mnt/info
EmbeddedCode 		PKG_ROOT="/usr/local/zy-pkgs"
EmbeddedCode 	else
EmbeddedCode 		PKG_ROOT=\`grep "\${PKG_NAME}" /etc/zyxel/pkg_conf/status |grep "Installed-Rule" |awk -F":" '{print \$2}' |sed 's|/$||g'|sed 's| ||g'\`
EmbeddedCode 	fi
EmbeddedCode }
EmbeddedCode 
__EOF__
		else
			StripEmbedded <<__EOF__
EmbeddedCode PKG_FIRMWARE=4
EmbeddedCode 
__EOF__
		fi
		AddIsUpgrading
		AddLoggingCode
		
		StripEmbedded <<__EOF__
EmbeddedCode IsUpgrading
EmbeddedCode Log \` [ \$PKG_UPGRADING -gt 0 ] && echo upgrading \`
EmbeddedCode 
__EOF__

		if [ "${script}" = "ReplaceRule" ] ; then
			StripEmbedded <<__EOF__
EmbeddedCode GetPkgRoot
EmbeddedCode sed -i "/^PKG_ROOT/s|/usr/local/zy-pkgs|\${PKG_ROOT}|" \${PKG_ROOT}/etc/init.d/\${PKG_NAME}
EmbeddedCode sed -i "s|^PKG_FIRMWARE=4|PKG_FIRMWARE=5|" \${PKG_ROOT}/etc/init.d/\${PKG_NAME}
EmbeddedCode 
EmbeddedCode INFODIR=\${PKG_ROOT}/zypkg_conf/info/
EmbeddedCode 
EmbeddedCode for file in \` ls \${INFODIR} \`
EmbeddedCode do
EmbeddedCode 	[ "\${file}" = "\${PKG_NAME}.\${THIS_SCRIPT}" ] && continue
EmbeddedCode 	sed -i "/^PKG_ROOT/s|/usr/local/zy-pkgs|\${PKG_ROOT}|" \${INFODIR}\${file}
EmbeddedCode 	sed -i "s|^PKG_FIRMWARE=4|PKG_FIRMWARE=5|" \${INFODIR}\${file}
EmbeddedCode done
EmbeddedCode 
__EOF__
		else # ReplaceRule
			StripEmbedded <<__EOF__
EmbeddedCode PKG_ROOT="/usr/local/zy-pkgs"
EmbeddedCode 
__EOF__
		fi # ! ReplaceRule

		if [ ! -z "${PRESERVE_FILES}" ] ; then	
			if [ "${script}" = "prerm" ] ; then
				StripEmbedded <<__EOF__
EmbeddedCode PreserveFiles()
EmbeddedCode {
EmbeddedCode 	local preserve_root=\${PKG_ROOT}
EmbeddedCode 	[ "\` basename \${preserve_root} \`" = "\${PKG_NAME}" ] && preserve_root=\` dirname \${preserve_root} \`
EmbeddedCode 	cd \${PKG_ROOT}
EmbeddedCode 	tar cf \${preserve_root}/preserve.\${PKG_NAME}.tar ${PRESERVE_FILES}
EmbeddedCode }
EmbeddedCode 
EmbeddedCode [ \${PKG_UPGRADING} -gt 0 ] && PreserveFiles
EmbeddedCode 
__EOF__

			fi # prerm
			
			if [ "${script}" = "postinst" ] ; then
				StripEmbedded <<__EOF__
EmbeddedCode PreserveFiles()
EmbeddedCode {
EmbeddedCode 	local preserve_root=\${PKG_ROOT}
EmbeddedCode 	[ "\` basename \${preserve_root} \`" = "\${PKG_NAME}" ] && preserve_root=\` dirname \${preserve_root} \`
EmbeddedCode 	local preserve_tar=\${preserve_root}/preserve.\${PKG_NAME}.tar
EmbeddedCode 	if [ -f \${preserve_tar} ] ; then
EmbeddedCode 		PRESERVED_FOUND=1
EmbeddedCode 		cd \${PKG_ROOT}
EmbeddedCode 		tar xf \${preserve_tar}
EmbeddedCode 		rm \${preserve_tar}
EmbeddedCode 	fi
EmbeddedCode }
EmbeddedCode 
EmbeddedCode PreserveFiles
EmbeddedCode
__EOF__
			fi # postinst
		fi # PRESERVE_FILES

		if [ "${script}" = "postinst" ] ; then
			local cssfile=${CURDIR}/${PACKAGENAME}/data/gui/${PACKAGENAME}/${PACKAGENAME}.css
			if [ -f ${cssfile} ] ; then
				local iconfiles="$( cat ${cssfile} | sed -n '/url/p' | \
				    sed 's|url(../../pkg|+|' | cut -d '+' -f 2 | \
				    cut -d ')' -f 1 | sort | uniq | tr '\n' ' ' )"
				iconfiles="${iconfiles} /${PACKAGENAME}/${PACKAGENAME}.css"
				StripEmbedded <<__EOF__
EmbeddedCode CopyDesktopIcons()
EmbeddedCode {
EmbeddedCode 	local pkgdir=/i-data/sysvol/.system/zy-pkgs
EmbeddedCode 	if [ -d \${pkgdir} ] ; then
EmbeddedCode 		pkgdir=\${pkgdir}/pkggui
EmbeededCode 		for file in ${iconfiles}
EmbeddedCode 		do
EmbeddedCode 			mkdir -p \$( dirname \${pkgdir}\${file} )
EmbeddedCode 			cp \${PKG_ROOT}/gui\${file} \${pkgdir}\${file}
EmbeddedCode 		done
EmbeddedCode 	fi
EmbeddedCode }
EmbeddedCode 
EmbeddedCode CopyDesktopIcons
EmbeddedCode 
__EOF__
			
			fi # ${PKG_NAME}.css
			

			if [ $CHECK_FOR_MEDION -eq 1  ] ; then
			StripEmbedded <<__EOF__
EmbeddedCode PKG_MEDION=0
EmbeddedCode  
EmbeddedCode if [ -f /zyxel/mnt/info/modelid ] ; then
EmbeddedCode 	case \` cat /zyxel/mnt/info/modelid \`
EmbeddedCode 	in
EmbeddedCode 		A403*)
EmbeddedCode 			PKG_MEDION=1
EmbeddedCode 			;;
EmbeddedCode 		A803*)
EmbeddedCode 			PKG_MEDION=1
EmbeddedCode 			;;
EmbeddedCode 		AB03*)
EmbeddedCode 			PKG_MEDION=1
EmbeddedCode 			;;
EmbeddedCode 	esac
EmbeddedCode fi
EmbeddedCode 	
EmbeddedCode [ \$PKG_MEDION -eq 1 ] && sed -i "s|^PKG_MEDION=0|PKG_MEDION=1|" \${PKG_ROOT}/etc/init.d/\${PKG_NAME}
EmbeddedCode 
__EOF__
			fi # CHECK_FOR_MEDION=1

			if [ "${PRESERVE_DOWNLOAD_URL}" != "" ] ; then
				StripEmbedded <<__EOF__
EmbeddedCode ExchangeDownloadUrl()
EmbeddedCode {
EmbeddedCode 	if [ -f /tmp/.MetaRepository/tmp/lasturl ] ; then
EmbeddedCode 		local url=\$(cat  /tmp/.MetaRepository/tmp/lasturl )
EmbeddedCode 		sed -i "s|^PKG_DOWNLOAD_URL=${PRESERVE_DOWNLOAD_URL}|PKG_DOWNLOAD_URL=\${url}|" \${PKG_ROOT}/etc/init.d/\${PKG_NAME}
EmbeddedCode 	fi
EmbeddedCode }
EmbeddedCode 
EmbeddedCode ExchangeDownloadUrl
EmbeddedCode 
__EOF__
			fi # PRESERVE_DOWNLOAD_URL
		fi # postinst
		
		if [ -f ${CURDIR}/${script} ] ; then
			cat ${CURDIR}/${script} 
		else
		    StripEmbedded <<__EOF__
EmbeddedCode # TODO
EmbeddedCode # Add your own code
__EOF__
		fi # ! user script

		[ "${script}" = "postinst" -a -f ${CURDIR}/hello ] && cat ${CURDIR}/hello

		exec 1>&3 ; exec 3>&-
		chmod 755 ${controlscript}
	done

	# control file
	echo ${control}/control...
	local datasize=` du -s ${rootdir}/data | awk '{print $1 }' `
	local controlsize=` du -s ${control} | awk '{ print $1 }' `
	local totalsize=
	let totalsize="(datasize+controlsize)*1024"
	local compressedsize=
	let compressedsize="(totalsize*3)/8"
	
	exec 3>&1 ; exec 1>${control}/control ; StripEmbedded <<__EOF__
EmbeddedCode Package: ${PACKAGENAME}
EmbeddedCode Version: ${PKG_VERSION}zypkg${PKG_REVISION}
EmbeddedCode Description: ${PKG_DESCRIPTION}
EmbeddedCode Depends: ${PKG_DEPENDS}
EmbeddedCode Size: ${compressedsize}
EmbeddedCode Installed-Size: ${totalsize}
EmbeddedCode Architecture: arm
EmbeddedCode Zy-Model: all
EmbeddedCode IsBuiltin: N
EmbeddedCode Filename: ${PACKAGENAME}_${PKG_VERSION}_arm_${PKG_REVISION}.zpkg
__EOF__
	exec 1>&3 ; exec 3>&-

	if [ "${PKG_CONFLICTS}" != "" ] ; then
	    exec 3>&1 ; exec 1>>${control}/control ; StripEmbedded <<__EOF__
EmbeddedCode Conflicts: ${PKG_CONFLICTS}
__EOF__
	    exec 1>&3 ; exec 3>&-
	fi

	
	if [ ${ENABLE_WEBINTERFACE} -eq 1 ] ; then
		# webinterface
		if [ "${CUSTOM_WEBINTERFACE}" = "\${PKG_ROOT}/gui/\${PKG_NAME}/" ] ; then
			local httproot=${rootdir}/data/gui/${PACKAGENAME}
			if [ ! -f ${httproot}/index.html -a ! -f ${httproot}/index.php ] ; then
				echo ${httproot}/index.html...
				mkdir -p ${httproot}

				exec 3>&1 ; exec 1>${httproot}/index.html ; StripEmbedded <<__EOF__
EmbeddedCode <html>
EmbeddedCode <head>
EmbeddedCode </head>
EmbeddedCode <body>
EmbeddedCode Automatically generated webinterface for ${PACKAGENAME}
EmbeddedCode </body>
EmbeddedCode </html>
__EOF__
				exec 1>&3 ; exec 3>&-
			fi
		fi
	fi
	
	# build script
	local script=${rootdir}/generate_package_tgz.sh
	echo ${script}
	exec 3>&1 ; exec 1>${script} 
	StripEmbedded <<__EOF__
EmbeddedCode #!/bin/sh
EmbeddedCode cd \` dirname \$0 \`
EmbeddedCode FILENAME=\` cat control/control | grep Filename | cut -d ' ' -f 2 \`
EmbeddedCode echo Generating \${FILENAME} and ZYPKGS
EmbeddedCode 
EmbeddedCode TAR=/tmp/.MetaRepository/bin/tar
EmbeddedCode [ -f \$TAR ] && DATAUSERNAME$$="--owner=${PKG_OWNER} --group=${PKG_GROUP}" ; CONTROLUSERNAME$$="--owner=admin --group=everyone" || TAR=tar
EmbeddedCode 
EmbeddedCode cd data
__EOF__
	if [ "${EXCHANGEVERSIONIN}" != "" ] ; then
	    StripEmbedded <<__EOF__
EmbeddedCode mkdir -p /tmp/data.$$.${PACKAGENAME}
EmbeddedCode for file in ${EXCHANGEVERSIONIN}
EmbeddedCode do
EmbeddedCode 	mkdir -p /tmp/data.$$.${PACKAGENAME}/\$( dirname \$file )
EmbeddedCode 	cp \$file /tmp/data.$$.${PACKAGENAME}/\$file
EmbeddedCode 	sed -i 's|__PKG_VERSION__|${PKG_VERSION}zypkg${PKG_REVISION}|g' \$file
EmbeddedCode done
__EOF__
	fi
	StripEmbedded <<__EOF__
EmbeddedCode \$TAR czf ../data.tar.gz \${DATAUSERNAME$$} *
__EOF__
	if [ "${EXCHANGEVERSIONIN}" != "" ] ; then
	    StripEmbedded <<__EOF__
EmbeddedCode for file in ${EXCHANGEVERSIONIN}
EmbeddedCode do
EmbeddedCode 	mv /tmp/data.$$.${PACKAGENAME}/\$file \$file
EmbeddedCode done
EmbeddedCode rm -fr /tmp/data.$$.${PACKAGENAME}
__EOF__
	fi
	StripEmbedded <<__EOF__
EmbeddedCode cd ../control
EmbeddedCode \$TAR czf ../control.tar.gz \${CONTROLUSERNAME$$} *
EmbeddedCode cd ..
EmbeddedCode \$TAR czf ../\${FILENAME} \${CONTROLUSERNAME$$} data.tar.gz control.tar.gz
EmbeddedCode rm data.tar.gz control.tar.gz
EmbeddedCode 
EmbeddedCode cp control/control ../ZYPKGS
EmbeddedCode md5=\` md5sum ../\${FILENAME} | cut -d ' ' -f 1 \`
EmbeddedCode echo MD5SUM: \${md5} >>../ZYPKGS
__EOF__
	exec 1>&3 ; exec 3>&-
	chmod a+x ${script}
	${script}
}





ReadConfigLine()
{
	case "$1" in
		packagename=*)
			PACKAGENAME=` echo $1 | cut -d '=' -f 2 `
			;;
		version=*)
			PKG_VERSION=` echo $1 | cut -d '=' -f 2 `
			;;
		revision=*)
			PKG_REVISION=` echo $1 | cut -d '=' -f 2 `
			;;
		targetdir=*)
			TARGETDIR=` echo $1 | cut -d '=' -f 2 `
			;;
		disable-webinterface)
			ENABLE_WEBINTERFACE=0
			;;
		custom-webinterface=*)
			CUSTOM_WEBINTERFACE=` echo $1 | cut -d '=' -f 2 `
			;;				
		custom-webalias=*)
			CUSTOM_WEBALIAS=` echo $1 | cut -d '=' -f 2 `
			;;
		conflicts=*)
			PKG_CONFLICTS="` echo $1 | cut -d '=' -f 2 - `"
			;;			
		preserve-over-update=*)
			local value=` echo $1 | cut -d '=' -f 2 `
			[ -z ${PRESERVE_FILES} ] && PRESERVE_FILES=${value} || PRESERVE_FILES="${PRESERVE_FILES} ${value}"
			;;
		enable-loginless)
			ENABLE_LOGINLESS=1
			;;
		depends-on=*)
			local value=` echo $1 | cut -d '=' -f 2 `
			[ -z ${PGK_DEPENDS} ] && PKG_DEPENDS=${value} || PKG_DEPENDS="${PKG_DEPENDS} ${value}"
			;;
		config-file=*)
			local value=` echo $1 | cut -d '=' -f 2 `
			[ -f ${value} ] && ParseConfigFile ${value} || echo ${value} not found
			;;
		enable-logfile)
			[ 2 -eq ${ENABLE_LOGFILE} ] && ENABLE_LOGFILE=3
			[ 1 -eq ${ENABLE_LOGFILE} ] && ENABLE_LOGFILE=2
			[ 0 -eq ${ENABLE_LOGFILE} ] && ENABLE_LOGFILE=1
			;;
		description=*)
			PKG_DESCRIPTION="` echo $1 | cut -d '=' -f 2- `"
			;;
		check-for-medion)
			CHECK_FOR_MEDION=1
			;;
		exchange-version-in=*)
			local value=` echo $1 | cut -d '=' -f 2 `
			EXCHANGEVERSIONIN="${value} ${EXCHANGEVERSIONIN}"
			;;
		owner=*)
			local value=` echo $1 | cut -d '=' -f 2 `
			PKG_OWNER=` echo $value | cut -d ':' -f 1 `
			PKG_GROUP=` echo $value | cut -d ':' -f 2 `
			;;
			
		preserve-download-url)
			PRESERVE_DOWNLOAD_URL=http://downloads.zyxel.nas-central.org/Users/Mijzelf/fw5
			;;

		*)
			echo "Unknown option $1"
			Help
			exit 1
			;;
	esac
}

ParseConfigFile() 
{
	while read line
	do
		[ "$line" = "" ] && continue
		case "$line" in
			\#*)
				continue
				;;
			*)
				ReadConfigLine "$line"
				;;
		esac
	done <$1
}

ReadConfig()
{
	while [ "$1" != "" ] ; 
	do
		case "$1" in
			--*)
				ReadConfigLine ${1:3}
				;;
			*)
				if [ "${PACKAGENAME}" != "" ] ; then
					echo "Unknown option $1"
					Help
					exit 1
				fi
				PACKAGENAME=$1
				;;
		esac
		shift
	done
	
	[ "${PACKAGENAME}" = "" -a -f config.conf ] && ParseConfigFile config.conf
}

Help()
{
	cat >&1 <<__EOF__
` basename $0 ` packagename <options>
Supported options
    --packagename=<packagename>
	Alternate way to assign packagename
    --targetdir=<dir> 
	Directory where the package will be created (in subdirectory <packagename>). Ddefault .
    --disable-webinterface
	Disable code for webinterface
    --enable-loginless 
	Enable webinterface without login.
    --version=<version>
	Package version. No funny characters, no underscores. Default YYYYMMDD of today
    --revision=<revision>
	Should be 001...999. Default 001
    --conflicts=<packagename>
	Conflicting package
    --preserve-over-update=<file>
	File which should be preserved on update. Can be applied more than once. This is handled by prerm and postinst.
	In postinst a variable PRESERVED_FOUND=1 will be set when preserved files were found
    --depends-on=<package>
	Can be applied more than once
    --check-for-medion
        Add a PKG_MEDION=0 or PKG_MEDION=1 in startscript and postinst, depending on if the box is a Medion
    --enable-logfile
	Enable code for logging to /tmp/<PKG_NAME>.log, if this file exists. By applying the option twice you'll get a more 
	verbose logs with environment and stackdumps and stuff.
    --owner=owner[:group]
	Owner&group of the files in the package. Default admin:everyone
    --config-file=file 
	Read config from file. The should contain one argument per line, without the leading --
    --exchange-version-in=file
        Exchange __PKG_VERSION__ in file by package version (relative to PKG_ROOT. Is applied by postinst. You can add this option
	more than once.y
    --preserve-download-url
	Create a variable PKG_DOWNLOAD_URL in the startscript, containing the download url of this package, as provided by MetaRepository

    Further the next files in the current directory are used, if they exist:
    preinst ReplaceRule postinst prerm postrm:
	content is added to generated control scripts
    startscript
	content is added to generated startscript. It can contain one or more of the functions Startup(), Shutdown(),
	GetLink(). The functions may be empty. 
	
	In the scripts you'll have the variables
	    PKG_ROOT		Root of the package
	    PKG_FIRMWARE	4 or 5
	    PKG_NAME		Name of the package_
    config.conf
	Is read for config when no packagename is provided
__EOF__
# '
}

PACKAGENAME=
ENABLE_WEBINTERFACE=1
ENABLE_LOGINLESS=0
ENABLE_LOGFILE=0
PKG_VERSION=` date +%Y%m%d `
PKG_REVISION=001
PKG_DESCRIPTION="Automatically generated empty package"
CHECK_FOR_MEDION=0
TARGETDIR="."
BASENAME=` basename $0 `
CURDIR=` pwd `
PKG_OWNER=admin
PKG_GROUP=everyone
EXCHANGEVERSIONIN=""
PRESERVE_DOWNLOAD_URL=""

ReadConfig "$@"

[ "${PACKAGENAME}" = "" ] && echo No packagename provided && Help && exit 1

GenerateEmptyProject

