#!/bin/bash -x

: ${TOPDIR:=/usr/src/packages}

container="buildcont"

set -e

echo "Generating OVA image from ISO from container image"

# Build service provides the container image as a .tar file

img=$(ls ${TOPDIR}/DOCKER/*.tar)

[ -f "${img}" ] || exit 1

# import .tar with buildah

buildah from --name "${container}"  "docker-archive:${img}"

# mount container to access its content

mnt=$(buildah mount "${container}")

# extract the image size from the "build config"

img_size=$(grep -m 1 "%img_size" ~/.rpmmacros | tr -d "\n" | cut -d " " -f 2)

# extract two last project path elements ({Stable,Staging,Dev}:TealXX)
# replace colon with dash
project=$(grep -m 1 "%_project" ~/.rpmmacros | tr -d "\n" | rev | cut -d ":" -f 1,2 | rev | tr ":" "-")

# create an empty image file and a respective loop device
dd if=/dev/zero of=ova.img bs=$((1*1024*1024)) count="${img_size}"
losetup /dev/loop42 ./ova.img
mkfs -t ext3 -L OVA_IMAGE /dev/loop42

# root partition
#
# create an EXT3 image
mkdir img
mount /dev/loop42 img

# copy the rootfs into this partition
cp -a $mnt/* img

# undo all mounts, loopback devices, etc.

umount img
rmdir img

losetup -d /dev/loop42

# copy the image as ova.raw (buildservice checks extensions)

mkdir -p "${TOPDIR}/OTHER"
vmdk-convert ova.img ova.vmdk
rm ova.img
mkova.sh --num-cpus 4 --mem-size 4096 --hw 20 os-image ova.vmdk
rm ova.vmdk
sha256sum os-image.ova > "${TOPDIR}/OTHER/os-image.ova.sha256"
mv os-image.ova "${TOPDIR}/OTHER"
ln "${TOPDIR}/OTHER/os-image.ova" "${TOPDIR}/OTHER/os-image-${project}-`date +'%Y%m%d%H%M%S'`.ova"

# release the container

buildah umount "${container}"
buildah rm "${container}"
