#!/usr/bin/bash

# Start Cloud image in qemu-kvm and wait until root's ssh is available.
# Copyright (C) 2015 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


. "/etc/eimg"/eimg.sh
. "/usr/share/eimg"/lib

# Should we be "no-op" command?
test -n "$EIMG_WAITED" && $EIMG_WAITED && exit 0

image=$1

workdir=$(mktemp -d "/tmp/$(id -n -u)-eimg-XXXXXX")
test -z "$workdir" && exit 1

cleanup()
{
    rm -rf "$workdir"
}
trap cleanup EXIT

echo "using $workdir"


virt-install \
    --os-variant "fedora-unknown" \
    --name "$eimg_virt_name" \
    --disk "$image" \
    --disk size=4 \
    --memory=2048 \
    --import \
    --rng /dev/urandom \
    --connect qemu:///system \
    --noautoconsole \
    --network network=default,model=virtio \
    --channel unix,target_type=virtio,name='org.qemu.guest_agent.0'

eimg_wait_for_ip
/usr/bin/wait-for-ssh "$eimg_ip"
