#!/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

# 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
rm -f /etc/apt/sources.list~
echo "Updating /etc/apt/sources.list file."
cp sources16.list /etc/apt/sources.list
if ( rgrep '14.04' /etc/lsb-release >/dev/null ); then
	sed -i 's@xenial@trusty@' /etc/apt/sources.list
elif ( rgrep '18.04' /etc/lsb-release >/dev/null ); then
	sed -i 's@xenial@bionic@' /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://@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

# migrate to Ubuntu 16.04 if needed
if ( rgrep '14.04' /etc/lsb-release >/dev/null ); then
	echo "Upgrading to Ubuntu 16.04."
	sed -i 's@trusty@xenial@' /etc/apt/sources.list
	apt-get update
	apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold" || apt-get install -f -y -o Dpkg::Options::="--force-confold"
	apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold" || apt-get install -f -y -o Dpkg::Options::="--force-confold"
	apt-get dist-upgrade -y -o Dpkg::Options::="--force-confold"
	apt-get autoremove -y
	echo "16.04 migration ok."
	echo "The server is rebooting, please wait at least 2 minutes"
	echo " before restarting the script to continue the configuration."
	echo "Date: $(date)."
	echo "Ignore the following message about reboot problem if any."
	reboot
	exit 1
fi
systemctl unmask nginx || true

# APT panel
if ( ! test -z ${SKYREACH_API_KEY} ); then
	echo "Adding skyreach.list to APT sources."
	wget -q "https://${SKYREACH_HOST}/media/public.gpg" -O- | sudo apt-key add -
	echo "deb https://${SKYREACH_HOST} packaging/apt/${SKYREACH_API_KEY}/" > /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
