#!/bin/bash

DEBUG=0
LOGPATH="/root/cloud-init-install.log"
FILEPATH="/etc/sysconfig/network-scripts/ifcfg-eth0"
ROUTEFILEPATH="/etc/sysconfig/network-scripts/route-eth0"
HOSTSFILEPATH="/etc/hosts"
if [ $DEBUG = 1 ]; then
  cp /etc/sysconfig/network-scripts/ifcfg-eth0 ifcfg-eth0.new
fi

function cdr2mask {
   # Number of args to shift, 255..255, first non-255 byte, zeroes
   set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
   [ $1 -gt 1 ] && shift $1 || shift
   echo ${1-0}.${2-0}.${3-0}.${4-0}
}

#Fix centos mirrorlist domain not working
sed -i 's|\#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
sed -i 's/mirrorlist/\#mirrorlist/g' /etc/yum.repos.d/CentOS-*

# Collect IP details
IPMASK=$(ip -o -4 a sh dev eth0|awk '{ print $4 }')
arrIPMASK=(${IPMASK//\// })
IP=${arrIPMASK[0]}
MASKPREF=${arrIPMASK[1]}
MASK=$(cdr2mask $MASKPREF)
GW=$(ip ro|grep default|awk '{print $3}')

# Edit interface config
#sed -i '/^#/d' ${FILEPATH}
#sed -i '1i # Created by cloud-init on instance boot automatically, do not edit.' ${FILEPATH}
#sed -i '2i #' ${FILEPATH}
sed -i -e '$a\' ${FILEPATH}
sed -i -e "s/\r//g" ${FILEPATH}
sed -i 's/BOOTPROTO=.*/BOOTPROTO=static/g' ${FILEPATH}
sed -i '/DEFROUTE/d' ${FILEPATH}
sed -i '/DNS1/d' ${FILEPATH}
sed -i '/DNS2/d' ${FILEPATH}
sed -i 's/IPV6INIT=.*/IPV6INIT=no/g' ${FILEPATH}
sed -i '/IPV6_DEFAULTGW=/d' ${FILEPATH}
#echo "IPADDR=$IP" >> ${FILEPATH}
#echo "NETMASK=$MASK" >> ${FILEPATH}
#echo "GATEWAY=$GW" >> ${FILEPATH}
echo "127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4" > ${HOSTSFILEPATH}
echo "::1         localhost localhost.localdomain localhost6 localhost6.localdomain6" >> ${HOSTSFILEPATH}

echo "$GW dev eth0" >> ${ROUTEFILEPATH}
echo "default via $GW" >> ${ROUTEFILEPATH}

if [ $DEBUG -eq 1 ]; then
  exit
fi
systemctl stop NetworkManager
systemctl disable NetworkManager
#systemctl disable cloud-config
#systemctl disable cloud-final
#systemctl disable cloud-init-local
#systemctl disable cloud-init
systemctl restart network
#hostnamectl set-hostname localhost.localdomain
NOW=$(date)
echo "Starting combox software installation on $NOW" >> $LOGPATH
# Proceed to installing software
yum -y update
#cp /boot/grub2/grubenv /root/
yum -y install wget
#cd /root
wget http://repo.combox.gr/kickstart/prerequirementsBeforeYumInstallCombox-1.0.0-1.x86_64.rpm
yum -y install prerequirementsBeforeYumInstallCombox-1.0.0-1.x86_64.rpm
yum -y install combox-server
#cp /root/grubenv /boot/grub2/
rm -rf /etc/localtime
ln -s /usr/share/zoneinfo/Europe/Athens /etc/localtime
NOW=$(date)
echo "Finished combox software installation on $NOW" >> $LOGPATH
reboot
