#!/bin/sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin

while [ $(systemctl status NetworkManager | grep "Active:" | awk '{print $2}') != "active" ]; do
  sleep 1
done 

while [ $(ping -c 1 130.238.96.1 2>/dev/null | grep 'bytes from' | awk 'END{print NR}') = "0" ]; do
 sleep 1
done

IFACE=$(for i in `ifconfig | awk '/^[a-zA-Z0-9]+/ {gsub(/:/, ""); print $1}'`; do if ifconfig $i | grep -q `ip route | awk '/default via/ {gsub(/\./, " "); print $3"."$4"."$5}'`; then echo $i; fi; done)
IPADDR=$(ifconfig ${IFACE} | awk '($1 == "inet") {sub(/:/, " "); print $3}')
NETMASK=$(ip route | grep `echo ${IPADDR} | awk -F '.' '{print $1"."$2"."$3".0"}'` | awk '{sub(/\//, " "); print $2}')
FULL_COMPUTERNAME=$(host `echo ${IPADDR}` | awk '{print $5}' | awk -F '.' '{print $1}')
DOMAIN_NAME=$(host `echo ${IPADDR}` | awk '{print $5}' | awk '{sub(/\.$/,"");printf("%s\n",substr($1,index($1,".")+1))}')
HOST_NAME=${FULL_COMPUTERNAME}.${DOMAIN_NAME}
if [ `echo ${FULL_COMPUTERNAME} | awk -F "-" '{print $1"-"$2"-"$3"-"$4}'` = "ovirt-0-1a-4a" ]; then
  SHORT_COMPUTERNAME=$(echo ${FULL_COMPUTERNAME} | awk -F "-" '{print $1"-"$5"-"$6"-"$7}')
  NETBIOS_COMPUTERNAME=$(echo ${SHORT_COMPUTERNAME} | awk '{print toupper ($1)}')
else
  NETBIOS_COMPUTERNAME=$(echo ${FULL_COMPUTERNAME} | awk '{print toupper ($1)}')
fi
SMBCONF="/etc/samba/smb.conf"
mount.cifs -o ro,sec=ntlmssp,user=vps_manager,password=Yujk..45a //storm.slu.se/owners$ /mnt/
SUDOER=$(grep "${HOST_NAME}" /mnt/owners.txt | awk '{print $1}')
umount /mnt
SUDOERS="/etc/sudoers"

hostnamectl set-hostname ${HOST_NAME}
hostnamectl set-hostname ${HOST_NAME} --static
systemctl restart rsyslog.service

sed -i -e "s/netbios name = ovirt/netbios name = ${NETBIOS_COMPUTERNAME}/" -e "s/interfaces = 0.0.0.0\/00/interfaces = ${IPADDR}\/${NETMASK}/" ${SMBCONF}
net ads join -n ${NETBIOS_COMPUTERNAME} -U vps_manager%Yujk..45a createcomputer="Core/ComputerAccounts/VPS"
systemctl restart winbind.service

while [ $(systemctl status winbind.service | grep "Active:" | awk '{print $2}') != "active" ]; do
  sleep 5
done
systemctl restart nmb.service
systemctl restart smb.service

if [ $(echo "${SUDOER}" | awk 'END{print NR}') -gt "0" ]; then
  sed -i "/root ALL=(ALL) ALL/{G;s/$/${SUDOER} ALL=(ALL) ALL/;}" ${SUDOERS}
  for GROUP in cdrom floppy sudo audio dip video plugdev netdev bluetooth scanner; do adduser ${SUDOER} ${GROUP}; done
fi

systemctl enable puppet
systemctl start puppet
puppet agent --enable
systemctl restart puppet

systemctl restart lightdm

rm -f /etc/systemd/system/default.target.wants/startup.service /etc/systemd/system/startup.service /usr/local/bin/startup
