#!/bin/sh

# Copyright (C) 2015 Algo Communication Products Ltd.

CUR_LIST=/opt/lanbox/cache/algo-install.list

# step 0: generate install.list
if [ ! -f install.list ]; then
	ls -1 *.ipk | cut -d'_' -f 1 | sort > install.list
fi

# step 1: exclude already installed packages with same version
INSTALLED=`/opt/lanbox/bin/pkgman -l`
echo ==============================
echo "installed packages to be excluded:"
echo $INSTALLED
for pkg in $INSTALLED; do
	rm -f "$pkg"_sh2.ipk
done
# firmware-version package only used for back compatibility
rm -f firmware-version*.ipk

# step 2: remove obsolete packages
# Always removing obsolete packages before installing new one to support
# file overlaps between packages to upgrade from a different product.
if [ ! -f $CUR_LIST ]; then
	mkdir -p /opt/lanbox/cache
	cp legacy-install.list $CUR_LIST
fi
OBSOLETE_PACKAGES=$(comm -23 $CUR_LIST install.list)

echo ==============================
echo "packages to be de-installed:"
echo -------------------
echo $OBSOLETE_PACKAGES
echo ==============================
# de-install packages not in the new firmware
[ ! -z "$OBSOLETE_PACKAGES" ] && dpkg -P $OBSOLETE_PACKAGES || :

# step 3: install all new/updated packages
UPGPKG=$(ls *.ipk 2>/dev/null)
if [ ! -z "$UPGPKG" ]; then
	echo ==============================
	echo "package to be upgrade:"
	echo -------------------
	ls -1 *.ipk
	echo ==============================
	dpkg -i *.ipk || :
else
	echo "no package to upgrade"
fi

# step 4: save install.list
cp install.list $CUR_LIST
cp firmware-version /opt/lanbox/default_conf/

[ -x /opt/lanbox/bin/apply-settings ] && /opt/lanbox/bin/apply-settings all
