#! /bin/bash -x

die() { echo >&2 "$*" ; exit 1 ; }

image=$1

libvirt_connections='
{% for host in groups["copr_hypervisor"] %}
{% for arch in ["p08", "p09", "x86"] %}
{% if arch in inventory_hostname %}
{% set acceptable = ["p08", "p09"] if arch in ["p08", "p09"] else [arch] %}
{% for check in acceptable %}
{% if check in hostvars[host]['inventory_hostname'] %}
    qemu+ssh://copr@{{ hostvars[host]['inventory_hostname'] }}/system
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
'

new_volume=$2
if test -z "$new_volume"; then
  image_prefix=copr-builder-$(uname -m)-
  new_volume=$image_prefix$(date +"%Y%m%d_%H%M%S")
fi

export VIRSH_DEFAULT_CONNECT_URI=

test -n "$image" || die "first argument (image) required"
test -f "$image" || die "image $image not found"

pool=images
for connection in $libvirt_connections; do
    virsh --connect="$connection" vol-create-as --pool "$pool" "$new_volume" 1M
    virsh --connect="$connection" vol-upload    --pool "$pool" "$new_volume" --sparse "$image"
done

case $(uname -m) in
ppc64le)
    # We are going to upload the same image to OpenStack
    . "{{ provision_directory }}/.rc-osuosl.sh"

    # Per osuosl stack admin suggestion, ad long BUILD state:
    #   If you want it faster, I recommend you upload it as raw otherwise the
    #   hypervisor has to import the image into Ceph every time you build a new
    #   VM.
    # (this decreases the BUILD time from 3 minutes to < 20s)
    file=/tmp/raw-image
    rm -rf "$file"
    qemu-img convert "$image" "$file"
    glance image-create \
        --name "$new_volume" \
        --disk-format raw \
        --container-format bare \
        --file "$file" --progress
    ;;
esac


echo "uploaded images $new_volume"
