#!/bin/bash
### OpenStack Initialization script ###

_ip=$(ip -br -4 -o addr show eth0 | /usr/bin/awk {'print $NF'} | awk -F/ {'print $1'})

_logger () {
_logfile='/root/eig-cloud-init.log'
_time=$(date "+%F %T")
echo [${_time}]" "$1 | tee -a ${_logfile}
}

_ip_check () {
while ! pgrep dhclient &> /dev/null; do
  sleep 5
done
if [[ -z ${_ip} ]]; then
   while [[ -z ${_ip} ]]; do
     _logger "IP not found... restarting network"
     killall -9 dhclient
     service network restart
     sleep 5
     _ip=$(ip -br -4 -o addr show eth0 | /usr/bin/awk {'print $NF'} | awk -F/ {'print $1'})
   done
elif [[ ${_ip} =~ ^(10\.|192\.168\.122) ]]; then
   _logger "IP is not public IP: ${_ip}"
   exit 1;
fi
if grep -q dhcp /etc/sysconfig/network-scripts/ifcfg-eth0; then
  killall -9 dhclient
  service network restart
fi
}

_license_check () {
if [ -f /usr/local/cpanel/cpanel.lisc ]; then
   _logger "removing cPanel license..."
   rm -f /usr/local/cpanel/cpanel.lisc
fi
}

_update_swap () {
if ! grep -q swap /etc/fstab; then
  _swapfile='/swapfile'
  _logger "making swap"
  dd if=/dev/zero of=${_swapfile} bs=1024 count=4194304
  chmod 600 ${_swapfile}
  mkswap ${_swapfile}
  swapon ${_swapfile}
  echo "${_swapfile} swap   swap    defaults    0 0" >> /etc/fstab
  _logger "make_swap: OK"
fi
}

_mysql () {
_logger "Calling /usr/local/bin/shuffle_mysql.bash"
/usr/local/bin/shuffle_mysql.bash
}

_accesshash () {
_logger "Creating access hash"
_hash='/root/.accesshash'
rm -f ${_hash}
_logger "Generating Hash File..."
while [[ -f /var/run/cpkeyclt.pid ]]; do
  if [[ -e /proc/$(cat /var/run/cpkeyclt.pid) ]]; then
    sleep 5
  else
    rm -vf /var/run/cpkeyclt.pid
  fi
done
/usr/local/cpanel/cpkeyclt
/usr/sbin/whmapi1 accesshash user=root generate=1
if [ ! -f ${_hash} ]; then
  _logger "Failed to generate  access hash"
  exit 1
fi
/usr/local/cpanel/scripts/convert_accesshash_to_token
_chash=$(perl -pe 'chomp;' ${_hash})
curl -k -m 10 -s https://custapi.unifiedlayer.com/servaccesshash -d "hash=${_chash}"
while [ $? -eq 1 ]; do
  sleep 5
  curl -k -m 10 -s https://custapi.unifiedlayer.com/servaccesshash -d "hash=${_chash}"
done
_logger "access hash pushed to HAL" 
}
_grow_fs () {
_logger "Resizing FS"
/usr/bin/cloud-init -f /etc/cloud/eig-cloud.cfg -d modules
}

_logger "Starting $0"
_ip_check
_grow_fs
_license_check
_update_swap
_accesshash
_mysql
_logger "Completed $0"
