#!/bin/sh
# ============================================================================
#
# This file is part of the 'Entware-ng' 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="Entware-ng"
THIS_SCRIPT="postinst"
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
}

#############################################################
## Internal function of Log. Find parent, and print cmdline of process 
#############################################################
FindParent()
{
	local id=${1}
	[ $id -eq 1 ] && return # process 1 is the root of all processes

	local ppid=` grep PPid /proc/$id/status | awk '{ print $2 }' `
	FindParent $ppid

	local cmdline=` cat /proc/$id/cmdline | tr '\0' ' ' `
	echo ${id}${INDENT}${cmdline}
	INDENT="${INDENT}*"
}

#############################################################
## Write some useful log to /tmp/.log. -if it exists
#############################################################
Log() 
{
	[ ! -f /tmp/${PKG_NAME}.log ] && return

	if [ "$1" = "bare" ] ; then
 		shift
		echo "${THIS_SCRIPT}: $@" >>/tmp/${PKG_NAME}.log
		return
	fi

	exec 3>&1 ; exec 4>&2 ; exec >>/tmp/${PKG_NAME}.log 2>/dev/null
	echo "#######################################"
	echo "## Script: ${THIS_SCRIPT}"
	echo "#######################################"
	echo -e "\tTime: ` date +%T `"
	[ "$1" != "" ] && echo -e "\tMessage: $@"
	echo -e "\tCall stack"
	INDENT="*"
	local tmpfile=/tmp/$$.${PKG_NAME}
	FindParent $$ >$tmpfile
	unset INDENT
	local line
	while read line
	do
	    echo -e "\t\t${line}" | tr '*' '\t'
	done <$tmpfile
	rm $tmpfile
	echo -e "\tCurdir: ` pwd `"
	[ -h $0 ] && echo -e "\tSymlink: $0 is a symlink to ` readlink $0 `"
	echo -e "\tEnvironment"
	printenv >$tmpfile
	while read line 
	do
	    echo -e "\t\t${line}"
	done <$tmpfile
	rm $tmpfile
	exec 2>&4 ; exec 4>&- ; exec 1>&3 ; exec 3>&-
}

IsUpgrading
Log ` [ $PKG_UPGRADING -gt 0 ] && echo upgrading `

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

PreserveFiles()
{
	local preserve_root=${PKG_ROOT}
	[ "` basename ${preserve_root} `" = "${PKG_NAME}" ] && preserve_root=` dirname ${preserve_root} `
	local preserve_tar=${preserve_root}/preserve.${PKG_NAME}.tar
	if [ -f ${preserve_tar} ] ; then
		PRESERVED_FOUND=1
		cd ${PKG_ROOT}
		tar xf ${preserve_tar}
		rm ${preserve_tar}
	fi
}

PreserveFiles


IsOldKernel()
{
	# Find current kernel version
	local kernelversion=$( uname -r )
	local kv1=$( echo $kernelversion | cut -d '.' -f 1 )
	local kv2=$( echo $kernelversion | cut -d '.' -f 2 )
	local kv3=$( echo $kernelversion | cut -d '.' -f 3 )

	let kv1=kv1*10000
	let kv2=kv2*100
	let kv3=kv3+kv2+kv1

	# if < 2.6.32 (default target of Entware), enable 'old kernel' functionality
	[ $kv3 -lt 20632 ] && return 0
	
	return 1
}

[ "${PKG_STICK}" != "1" ] && IsOldKernel && sed -i "s|^PKG_OLDKERNEL=0|PKG_OLDKERNEL=1|" ${PKG_ROOT}/etc/init.d/${PKG_NAME}


infodir=/zyxel/mnt/info
[ -d /firmware/mnt/info ] && infodir=/firmware/mnt/info
model=unknown
[ -f /etc/modelname ] && model=` head -n 1 /etc/modelname `
modelid=` cat ${infodir}/modelid `
fwversion=` cat ${infodir}/fwversion `

stick=""
[ "${PKG_STICK}" = "1" ] && stick="-stick-$PKG_VERSION"

[ "${PKG_UPGRADING}" != "" -a ${PKG_UPGRADING} -gt 0 ] && upgrading="-upgrading"


# Say hello to the author of this package. The requested file doesn't exist, 
# so wget will get a 404, but it will give a logline in my webserver logs.
wget -q -t 2 -T 2 "http://mijzelf.duckdns.org/hello_author.php?${PKG_NAME}${upgrading}-${model}-${modelid}-${fwversion}${stick}" -O - 2>/dev/null

# get return value on zero again:
cat /proc/self/cmdline >/dev/null

