#!/bin/sh
# Copyright (C) 2014-2018 Algo Communication Products Ltd.

# allow libc to be updated
for pkg in libc-bin libc6 locales multiarch-support; do
	echo "$pkg install" | dpkg --set-selections
done

# remove any existing list to prevent mixing with debian repository
> /etc/apt/sources.list
rm -f /etc/apt/sources.list.d/*

APTGET_OPTIONS='-m -q -y --force-yes --no-install-recommends'
echo "deb file:$PWD/pool ./" > /etc/apt/sources.list.d/algo-upgrade.list

# remove docs to save space
if [ ! -f /etc/dpkg/dpkg.cfg.d/01_nodoc ]; then
	cp dpkg-nodoc /etc/dpkg/dpkg.cfg.d/01_nodoc
	rm -rf /usr/share/locale/* /usr/share/man/*
	find /usr/share/doc -type f -not -name 'copyright' -print0 | \
		xargs -0 rm --
fi

apt-get update
# For some reason, dpkg options cannot be passed as an env variable
apt-get $APTGET_OPTIONS -o Dpkg::Options::="--force-confold" dist-upgrade

if [ -f install.list ]; then
	while read pkg; do
		# remove comments
		if ! echo $pkg | egrep -q '^ *#'; then
			apt-get $APTGET_OPTIONS \
				-o Dpkg::Options::="--force-confold" \
				install $pkg
		fi
	done < install.list
fi

if [ -f remove.list ]; then
	while read pkg; do
		# remove comments
		if ! echo $pkg | egrep -q '^ *#'; then
			apt-get $APTGET_OPTIONS purge $pkg
		fi
	done < remove.list
fi

apt-get $APTGET_OPTIONS autoremove

# prevent libc to be updated from official debian repository
for pkg in libc-bin libc6 locales multiarch-support; do
	echo "$pkg hold" | dpkg --set-selections
done

mkdir -p /opt/algo/info
cp sys-version /opt/algo/info/sys-version
rm -f /etc/apt/sources.list.d/algo-upgrade.list

# enable/disable system services if necessary
READCONF=/opt/algo/bin/readconf
if [ "$($READCONF net.srv.snmp)" = "1" ]; then
	insserv -f snmpd
else
	insserv -f -r snmpd
fi

if [ "$($READCONF net.ssh)" = "1" ]; then
	insserv -f ssh
else
	insserv -f -r ssh
fi

if [ "$($READCONF net.telnet)" = "1" ]; then
	insserv -f openbsd-inetd
else
	insserv -f -r openbsd-inetd
fi

if [ "$($READCONF admin.watchdog)" = "1" ]; then
	insserv -f watchdog
else
	insserv -f -r watchdog
	insserv -f -r wd_keepalive
fi

DNS_CACHE=$($READCONF net.dns.cache)
if [ "$DNS_CACHE" = "" ] || [ "$DNS_CACHE" = "0" ]; then
	insserv -f -r unbound
else
	insserv -f unbound
fi

# generate checksums for any new packages
debsums --generate=all -p $PWD/pool > /dev/null
