#!/bin/sh
#Debian:
# cd /tmp/; \
# wget  http://{{OsImage.Server}}/osimages/pefiles/initpe.sh; \
# chmod +x initpe.sh; \
# ./initpe.sh {{OsImage.Server}} {{OsDeployment.Id}} {{Computer.Id}}; \
# wget http://{{OsImage.Server}}/osimages/pefiles/errpe.sh ; \
# chmod +x errpe.sh; \
# ./errpe.sh {{OsImage.Server}} {{OsDeployment.Id}} {{Computer.Id}} &
# d-i preseed/late_command string \
# cd /tmp/; \
# wget http://{{OsImage.Server}}/osimages/pefiles/fipe.sh ; \
# chmod +x fipe.sh; \
# ./fipe.sh {{OsImage.Server}} {{OsDeployment.Id}} {{Computer.Id}}
############ variables  ###########
httpserver=${1}
deploymentid=${2}
minionid=${3}
mqserver="10.21.66.5"
saltsrv="10.21.66.5"
ipxeserver="10.21.66.5:8081"
vhost="/"
exchange="os-deployment-result"
routingkey="os-deployment-result"
pelog="/tmp/peclient.log"
################################
cd /tmp/
interface=$(ip route show default | grep default | sed -n '1p' | cut -d " " -f5)
macaddr=$(cat /sys/class/net/$interface/address)
macaddr=$(echo $macaddr | sed -e 's/:/-/g')
echo $interface >>$pelog
echo $macaddr >>$pelog
echo "Started send start message script" >>$pelog
#############  workaround for wrong responce file  #########
if test -z "$minionid"; then	
	wget http://${ipxeserver}/osdeployment/ipxe/$macaddr.ipxe -O config.ipxe 2>>$pelog || curl http://${ipxeserver}/osdeployment/ipxe/$macaddr.ipxe -o config.ipxe 2>>$pelog
	minionid=$(cat config.ipxe | grep minionid -m 1 | sed -nE 's/#minionid=(.*)/\1/p')
	deploymentid=$(cat config.ipxe | grep deploymentid -m 1 | sed -nE 's/#deploymentid=(.*)/\1/p')
	httpserver=$(cat config.ipxe | grep kernel -m 1 | sed -nE 's/kernel http:\/\/(.*)\/osimages.*/\1/p')
fi
################################################################

if [ ! -f rmqclient ]; then
	wget http://${httpserver}/osimages/pefiles/rmqclient 2>>$pelog || curl http://${httpserver}/osimages/pefiles/rmqclient -o rmqclient 2>>$pelog
fi

zone=$(date +%z | sed 's/./&:/3')
datetime=$(date +%Y-%m-%dT%H:%M:%S.000000)
dateofstart=$datetime$zone
msg_start="{
	\"minionid\": $minionid,
	\"deploymentid\": $deploymentid ,
	\"status\": \"Start\",
	\"statusDesc\": \"Deployment started\",
	\"invokedOn\": \"$dateofstart\"
}
"
echo "Message to Colibri:" >>$pelog
echo "$msg_start" >>$pelog
echo "Executing rmqclient -h $mqserver -v $vhost -e $exchange -r $routingkey $msg_start" >>$pelog
chmod +x rmqclient
./rmqclient -h $mqserver -v $vhost -e $exchange -r $routingkey "$msg_start" 2>>$pelog
