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

# hostname
echo "127.0.0.1       ${ETC_HOSTNAME}" >> /etc/hosts
echo ${ETC_HOSTNAME} > /etc/hostname

# DNS
cat > /etc/resolv.conf << EOF
search ubicast.net
nameserver 192.168.40.3
nameserver 192.168.40.2
nameserver 192.168.40.6
EOF

# set ubicast account pwd
echo -e "${UBICAST_PASSWD}\n${UBICAST_PASSWD}" | (passwd -q ubicast)

# create admin account
useradd -m admin --shell /bin/bash 
echo -e "${SHELL_PWD}\n${SHELL_PWD}" | (passwd -q admin)
usermod -aG sudo admin

# migrate to Ubuntu 16.04 / apply sources.list
if [ $(cat /etc/lsb-release | grep DISTRIB_RELEASE | awk -F "=" '{print$2}') = "16.04" ]
then
cp sources16.list /etc/apt/sources.list
# Ubuntu 14.04
else
apt-get update && apt-get 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
fi

# màj
apt-get update && apt-get install -y aptitude && aptitude upgrade -y
aptitude install -y apt-transport-https pwgen ntpdate

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

# APT panel
wget -q https://${PANEL}/media/public.gpg -O- | sudo apt-key add -
echo "deb https://${PANEL} packaging/apt/${API}/" > /etc/apt/sources.list.d/skyreach.list
aptitude update

# unattended-upgrades
aptitude 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
