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

# migrate to Ubuntu 16.04 / apply sources.list
if ( rgrep '14.04' /etc/lsb-release >/dev/null ); then
	echo "Upgrading to Ubuntu 16.04."
	apt-get update
	apt-get dist-upgrade -y
	cp sources16.list /etc/apt/sources.list
	apt-get update
	DEBIAN_FRONTEND=noninteractive /usr/bin/apt-get dist-upgrade -o Dpkg::Options::="--force-confold" --force-yes -y
	apt-get install -f -y
	apt-get dist-upgrade -y
else
	echo "Updating Ubuntu 16.04 sources.list."
	cp sources16.list /etc/apt/sources.list
fi

# update
apt-get update
apt-get install -y apt-transport-https

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

# 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

# APT proxy
if [ ${PROXY} = "1" ]; then
	if [ ${PROXY_AUTHENTICATION} = "1" ]; then
		# general settings
		echo "Proxy: http://${PROXY_USER}:${PROXY_PWD}@${PROXY_HTTP}:${PROXY_PORT}" >> /etc/apt-cacher-ng/acng.conf
	else
		# general settings
		echo "Proxy: http://${PROXY_HTTP}:${PROXY_PORT}" >> /etc/apt-cacher-ng/acng.conf
	fi
fi

apt-get update

# unattended-upgrades
echo "Installing and configuring unattended-upgrades."
apt-get install -y unattended-upgrades
sed -i 's@//Unattended-Upgrade::Mail "root";@Unattended-Upgrade::Mail "root";@' /etc/apt/apt.conf.d/50unattended-upgrades
sed -i 's@//*.*"vim";@"mysql-server";@' /etc/apt/apt.conf.d/50unattended-upgrades
sed -i 's@//*.*"libc6";@"mysql-client";@' /etc/apt/apt.conf.d/50unattended-upgrades
# configure frequence
cat > /etc/apt/apt.conf.d/10periodic << EOF
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
EOF

# resolvconf
apt-get purge -y resolvconf
