#!/bin/bash
source /root/envsetup/global-conf.sh

DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND

apt-get update
apt-get install -y apt-transport-https gnupg lsb-release

# move 50unattended-upgrades conf if any
if [ -f '/etc/apt/apt.conf.d/50unattended-upgrades.ucf-dist' ]; then
	mv '/etc/apt/apt.conf.d/50unattended-upgrades.ucf-dist' '/etc/apt/apt.conf.d/50unattended-upgrades'
fi

# update sources.list
if ( ! test -f '/etc/apt/sources.list.save' ); then
	cp -a '/etc/apt/sources.list' '/etc/apt/sources.list.save'
fi
rm -f /etc/apt/sources.list~
if ( lsb_release -a | grep 'Ubuntu' >/dev/null 2>&1 ); then
	echo 'Updating /etc/apt/sources.list file.'
	cp 'sources-ubu.list' '/etc/apt/sources.list'
	if ( lsb_release -a | grep '14.04' >/dev/null 2>&1 ); then
		sed -i 's@bionic@trusty@' /etc/apt/sources.list
	elif ( lsb_release -a | grep '16.04' >/dev/null 2>&1 ); then
		sed -i 's@bionic@xenial@' /etc/apt/sources.list
	fi
else
	# Debian
	cp 'sources-deb.list' '/etc/apt/sources.list'
fi

# modify sources.list to use ubicast cache
if ( ! test -z ${APT_CACHE_URL} ); then
	if ( ! grep "${APT_CACHE_URL}" /etc/apt/sources.list >/dev/null ); then
		echo "Updating /etc/apt/sources.list to use cache ${APT_CACHE_URL}."
		sed -i "s@http://@${APT_CACHE_URL}@" /etc/apt/sources.list
	fi
fi

# update packages
apt-get update
apt-get install -f -y -o Dpkg::Options::="--force-confold"
apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold"
apt-get install -y apt-transport-https
apt-get autoremove -y

# APT panel
if ( ! test -z ${SKYREACH_APT_TOKEN} ); then
	echo "Adding skyreach.list to APT sources."
	wget -q "https://${SKYREACH_HOST}/media/public.gpg" -O- | apt-key add -
	echo "deb https://${SKYREACH_HOST} packaging/apt/${SKYREACH_APT_TOKEN}/" > /etc/apt/sources.list.d/skyreach.list
fi

# update
apt-get update
apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold"

# unattended-upgrades
apt-get install -y unattended-upgrades

# remove old kernels
echo 'Unattended-Upgrade::Remove-Unused-Dependencies "true";' >> /etc/apt/apt.conf.d/50unattended-upgrades
