#!/bin/sh

set -e


if [ -r /etc/fuel-bootstrap-iso/config ] ; then
	. /etc/fuel-bootstrap-iso/config
fi
# Manage parameters
if [ -n "${MASTER_NODE_IP}" ] ; then
	IP_ADDRESS=${MASTER_NODE_IP}
else
	IP_ADDRESS=10.20.0.2
fi

for i in $@ ; do
	case "${1}" in
	"-i")
		IP_ADDRESS=${2}
		shift
		shift
		;;
	*)
		echo "Parameter not recognized."
		;;
	esac
done

# Generate an ssh key if it's not already there
if ! [ -e /root/.ssh/id_rsa ] ; then
	if [ -e /root/.ssh/id_rsa.pub ] ; then
		echo "There's a /root/.ssh/id_rsa.pub but no /root/.ssh/id_rsa"
		echo "fix this and re-run the script"
		exit 1
	fi
	echo "No ssh key in /root/.ssh/id_rsa: generating one!"
	ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa
fi
# Copy the host's public key in the bootstrap image
cp /root/.ssh/id_rsa.pub /var/lib/fuel-bootstrap-iso/config-live-build/config/includes.chroot/root/.ssh/authorized_keys2
chmod 600 /var/lib/fuel-bootstrap-iso/config-live-build/config/includes.chroot/root/.ssh/authorized_keys2

# TODO: fix this and replace it by generated passwords
FUEL_PARMS="mco_user=mcollective mco_pass=marionette url=http://${IP_ADDRESS}"

# Do the actual live build of the image
cd /var/lib/fuel-bootstrap-iso/config-live-build
lb clean
lb config -b netboot --bootappend-live "boot=live systemd.show_status=true components $FUEL_PARMS fetch=http://${IP_ADDRESS}/fuel-bootstrap-iso/filesystem.squashfs" --net-root-path "/var/lib/fuel-bootstrap-iso" --net-root-server ${IP_ADDRESS}
lb build

# Extract the resulting pxeboot config so that dnsmasq can use it
mkdir -p /var/lib/fuel-bootstrap-iso/fs
tar -C /var/lib/fuel-bootstrap-iso/fs -xvf live-image-amd64.netboot.tar
