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

# migrate to Ubuntu 16.04 / apply sources.list
if ( cat /etc/lsb-release | grep '14.04' ); then
	# upgrade 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
	# Ubuntu 16.04
	cp sources16.list /etc/apt/sources.list
fi

# update
apt-get update
apt-get install -y aptitude apt-transport-https
apt-get dist-upgrade -y

# modify sources.list to use ubicast cache
grep ${APT_CACHE_HOST} /etc/apt/sources.list
if [ $? = 1 ]; then
	sed -i "s@http://@http://${APT_CACHE_HOST}/@" /etc/apt/sources.list
fi

# APT panel
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
apt-get update

# 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
aptitude purge -y resolvconf
