#!/bin/sh
set -x

: ${TOPDIR:=/usr/src/packages}
TARGET_DIR=$TOPDIR/KIWI-vmx/
RPM_SOURCE_DIR=$TOPDIR/SOURCES

cd $TARGET_DIR

# Compute the qcow2 filename
ARCH=$(uname -m)
IMG=$(ls *.$ARCH-*.qcow2)
IMG_NAME=$(echo $IMG | sed "s/.$ARCH-/\//" | cut -f1 -d '/')
IMG_VERSION=$(echo $IMG | sed 's/.x86_64-/\//; s/^[^/]\+\/\([^-]\+\).qcow2/\1/')

# If we don't have the corresponding .virtbuilder.template, then stop
TEMPLATE=$RPM_SOURCE_DIR/$IMG_NAME.virtbuilder.template
if ! test -f "$TEMPLATE"; then
    exit 0
fi

# xz compress the file
xz --best -k $IMG

# the file size
SIZE=$(stat -c %s $IMG.xz)

# the file sha512sum
CHECKSUM=$(sha512sum $IMG.xz | awk '{print $1}')

# HACKY Get the release version.
RELEASED_FILE=$(cd $TOPDIR/KIWI ; ls $IMG_NAME.$ARCH-$IMG_VERSION-Build*.qcow2 ; cd $OLDPWD)
RELEASE=$(echo $RELEASED_FILE | sed -e "s/^$IMG_NAME\.$ARCH-$IMG_VERSION-Build\([0-9.]\+\)\.qcow2$/\1/")

# Compute the revision from the version and release 2.0.1 / 11.1  -> 201111
REVISION=$(echo $IMG_VERSION$RELEASE | tr -d '.' | sed -e 's/^0\+\([1-9][0-9]*\)/\1/')
FILE=$IMG_NAME.$ARCH-$IMG_VERSION-Build$RELEASE

# Virtual size
VIRTUAL_SIZE=$(qemu-img info --output json $IMG | grep virtual-size | tr -d ' ,' | cut -d ':' -f2)

# Create the part from the index.part.in
sed -e "s/__FILE__/$FILE.qcow2.xz/g" \
    -e "s/__SIZE__/$SIZE/g" \
    -e "s/__VIRTUAL_SIZE__/$VIRTUAL_SIZE/g" \
    -e "s/__ARCH__/$ARCH/g" \
    -e "s/__CHECKSUM__/$CHECKSUM/g" \
    -e "s/__REVISION__/$REVISION/g" \
    < "$TEMPLATE" \
    > $IMG_NAME.$ARCH-$IMG_VERSION.index

echo "Bundle $FILE.qcow2.xz and $FILE.index"
cp $IMG.xz $TOPDIR/KIWI/$FILE.qcow2.xz
cp $IMG_NAME.$ARCH-$IMG_VERSION.index $TOPDIR/KIWI/$FILE.index
