#!/bin/bash

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

KIWI_NG=$( kiwi --version|grep "next generation")
KIWI_VER=$( kiwi --version | grep vnr | sed 's/.*vnr: //' )

echo "Running containment-rpm-docker: KIWI VERSION: $KIWI_VER"

set -e
set -u

IMAGE_DIR=$TOPDIR/KIWI
BUILD_DIR=/usr/lib/build
BUILD_DISTURL=

# To get BUILD_DISTURL
test -f /.buildenv && . /.buildenv

cd $IMAGE_DIR

# Setting default for SPEC_IN
SPEC_IN=$BUILD_DIR/image.spec.in

# Overwrite default for SPEC_IN if _image.spec.in
# exists in sources dir
if [ -f $TOPDIR/SOURCES/_image.spec.in ];then
    SPEC_IN=$TOPDIR/SOURCES/_image.spec.in
fi

echo "Using $SPEC_IN as spec file template"

echo "Generate metadata for spec file template"

ARCH=$( rpm --eval '%{_arch}')

# Parse KIWI config.xml to get docker images details
PKG_NAME=$( xmllint --xpath "string(//image/@name)" \
                    $TOPDIR/KIWIROOT-docker/image/config.xml )
PKG_VERSION=$( xmllint --xpath "string(//image/preferences/version)" \
                    $TOPDIR/KIWIROOT-docker/image/config.xml )
CONTAINER_RAW=$( xmllint --xpath "string(//image/preferences/type/containerconfig/@name)" \
                    $TOPDIR/KIWIROOT-docker/image/config.xml )
CONTAINER_TAG=$( xmllint --xpath "string(//image/preferences/type/containerconfig/@tag)" \
                    $TOPDIR/KIWIROOT-docker/image/config.xml )
CONTAINER_NAME=$(echo $CONTAINER_RAW | sed 's/\//-/' )

# Get path for python based kiwi
PREFIX="${PKG_NAME}.${ARCH}-${PKG_VERSION}"
SUFFIX=".tar.xz"
if [ -n "$KIWI_NG" ]; then
    SUFFIX=".docker${SUFFIX}"
fi

shopt -s nullglob
shopt -s extglob

IMAGE=$(echo ${PREFIX}*${SUFFIX})
METADATA=$(echo ${PREFIX}.metadata)
TAGFILE=$(echo ${PREFIX}.tag)
PACKAGES=$(echo ${PREFIX}*.packages)

if [ -z "$IMAGE" ]; then
    echo "Couldn't find anything in "`pwd`" matching ${PREFIX}*${SUFFIX}."
    echo "Content of directory: "
    echo "`ls -1`"
    echo "Will skip containment rpm wrapping steps."
    exit 0
fi

if [ -z "$CONTAINER_TAG" ]; then
    echo "Couldn't parse the container tag in config.xml"
    echo "Wrapping the image in a containment rpm requires a tag."
    echo "Will skip containment rpm wrapping steps."
    exit 0
fi

echo "Attempting to wrap $IMAGE in a containment rpm ..."

SUSE_VERSION="${CONTAINER_TAG}"
SUSE_PRODUCT_NAME="${CONTAINER_NAME}"

NAME="${CONTAINER_NAME}-image"
VERSION="${PKG_VERSION}"
RELEASE=$(echo "$PACKAGES" | sed 's/.*-Build\(.*\).packages/\1/')

if [ -z "$RELEASE" ]; then
    echo "Could not parse release number, setting it to zero"
    RELEASE=0
fi

# For some time our images where named <name>-docker-image,
# now they have been renamed to <name>-image.
# We have to obsolete the old names otherwise both RPMs will live
# on the same system. That can lead to issues with CaaSP, see bsc#1066653
OLD_NAME="${CONTAINER_NAME}-docker-image"

# Check if VERSION was defined properly and validate it
# VERSION for RPM package has to be decimal number separete with dots
if ! [[ $VERSION =~ ^([0-9]+\.){0,2}(\*|[0-9]+)$ ]]; then
    echo "Local build detected or wrong version format"
    # Just arbitrarily assign the version since we have nothing else
    # to go on.
    VERSION="1.0.0"
fi

echo "name $NAME"
echo "old name $OLD_NAME"
echo "version $VERSION"
echo "release $RELEASE"
echo "source $IMAGE"
echo "metadata $METADATA"
echo "tagfile $TAGFILE"

# Generate metada JSON file for container-feeder
cat << EOF > $METADATA
{
  "image": {
    "name": "$CONTAINER_RAW",
    "tags": [ "$CONTAINER_TAG", "${CONTAINER_TAG}-${RELEASE}", "latest" ],
    "file": "$IMAGE"
  }
}
EOF

# Generate tagfile for automation to determine the latest, most specific, tag for
# the currently installed RPM
echo -n "${CONTAINER_TAG}-${RELEASE}" > $TAGFILE

# Keep __SLE_VERSION__ in there for backwards compatiblity
# with older spec file templates
sed -e "s/__NAME__/$NAME/g" \
    -e "s/__OLD_NAME__/$OLD_NAME/g" \
    -e "s/__PKG_NAME__/$PKG_NAME/g" \
    -e "s/__VERSION__/$VERSION/g" \
    -e "s/__RELEASE__/$RELEASE/g" \
    -e "s/__SOURCE0__/$IMAGE/g" \
    -e "s/__SOURCE1__/$METADATA/g" \
    -e "s/__SOURCE2__/$TAGFILE/g" \
    -e "s/__SLE_VERSION__/$SUSE_VERSION/g" \
    -e "s/__SUSE_VERSION__/$SUSE_VERSION/g" \
    -e "s/__SUSE_PRODUCT_NAME__/$SUSE_PRODUCT_NAME/g" \
    < $SPEC_IN \
    > $BUILD_DIR/image.spec

touch $BUILD_DIR/image.changes

echo "Generating changelog for $PKG_NAME $ARCH"

CHANGELOG_FILENAME=/usr/share/changelog-generator-data/old.changes.$PKG_NAME.$ARCH
PACKAGES_FILENAME=/usr/share/changelog-generator-data/old.packages.$PKG_NAME.$ARCH

if [ -e $PACKAGES_FILENAME ];then
    if [ -e $CHANGELOG_FILENAME ];then
        if ! type changelog-generator &>/dev/null;then
            echo "Fatal: changelog found but 'changelog-generator' not installed!"
            exit 1
        fi

        changelog-generator --new-packages $PACKAGES \
          --old-packages $PACKAGES_FILENAME \
          --changelog $CHANGELOG_FILENAME > $BUILD_DIR/image.changes
    else
        echo "no $PACKAGES_FILENAME"
    fi
else
    echo "no $CHANGELOG_FILENAME"
fi

cat $BUILD_DIR/image.changes >> $BUILD_DIR/image.spec
mv $BUILD_DIR/image.changes $IMAGE_DIR

# Copy metadata file to source directory
if [ ! -f $TOPDIR/SOURCES/$METADATA ]; then
  cp $METADATA $TOPDIR/SOURCES
fi

# Copy tagfile to source directory
if [ ! -f $TOPDIR/SOURCES/$TAGFILE ]; then
  cp $TAGFILE $TOPDIR/SOURCES
fi

# Local builds have the file already in place, that's not true on IBS
if [ ! -f $TOPDIR/SOURCES/$IMAGE ]; then
  ln $IMAGE $TOPDIR/SOURCES
fi

# Make sure /usr/src/packages/* dirs exist
if [ ! -f $TOPDIR/BUILD ]; then
  echo "Create BUILD dir"
  mkdir -p $TOPDIR/BUILD
fi

if [ ! -f $TOPDIR/SRPMS ]; then
  echo "Create SRPMS dir"
  mkdir -p $TOPDIR/SRPMS
fi

if [ ! -f $TOPDIR/RPMS/$ARCH ]; then
  echo "Create SRPMS dir"
  mkdir -p $TOPDIR/RPMS/$ARCH
fi

if [ -z "$BUILD_DISTURL" ]; then
  rpmbuild -ba $BUILD_DIR/image.spec
else
  rpmbuild -ba --define "disturl $BUILD_DISTURL" $BUILD_DIR/image.spec
fi

# required for the BS to find the rpm, because it is
# a "non-standard result file for KIWI"
mkdir -p $TOPDIR/OTHER
mv $TOPDIR/RPMS/$ARCH/$NAME-$VERSION-$RELEASE.$ARCH.rpm $TOPDIR/OTHER/
mv $TOPDIR/SRPMS/$NAME-$VERSION-$RELEASE.src.rpm $TOPDIR/OTHER/
