#!/bin/bash

set -e
set -u

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

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

# To get BUILD_DISTURL
# shellcheck disable=SC1091
test -f /.buildenv && . /.buildenv

[ -d "$IMAGE_DIR" ] || exit 0
cd "$IMAGE_DIR"

set +e # we have set -e, so on Minimal VMs this needs to fail silently
ISO=$(ls -1 /usr/src/packages/KIWI/SLE*Migration*.iso 2>/dev/null)
set -e

if [ -z "$ISO" ]; then
    echo "Couldn't find anything in $IMAGE_DIR matching SLE*Migration*.iso"
    echo "Will skip containment rpm wrapping steps."
    exit 0
fi

IMAGE=${ISO##*/}
ARCH="$(uname -m)"
NAME=$(echo "$IMAGE" | cut -f1 -d.)
VERSION=$(echo "$IMAGE" | cut -f3 -d-)
RELEASE=$(echo "$IMAGE" | cut -f4 -d- | sed -e "s@Build@@" | sed -e 's@.iso$@@')
PRODUCT='product(SLES) >= %{MinSLEVersion}'

# SAP product check
if echo "$NAME" | grep -q SAP_; then
    PRODUCT='product(SLES_SAP) >= %{MinSLEVersion}'
fi

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

echo "name: $NAME"
echo "version: $VERSION"
echo "release: $RELEASE"
echo "product: $PRODUCT"

sed -e "s/__NAME__/$NAME/g" \
    -e "s/__VERSION__/$VERSION/g" \
    -e "s/__RELEASE__/$RELEASE/g" \
    -e "s/__SOURCE__/$IMAGE/g" \
    -e "s/__PRODUCT__/$PRODUCT/g" \
    < $BUILD_DIR/image.spec.in \
    > $BUILD_DIR/image.spec

if [ -f /.build-changelog ]; then
  cp /.build-changelog $BUILD_DIR/image.changes
  $BUILD_DIR/changelog2spec --target rpm --file $BUILD_DIR/image.changes >> $BUILD_DIR/image.spec
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

echo "Starting build"

if [ -z "$BUILD_DISTURL" ]; then
  rpmbuild --target "$ARCH" -ba "$BUILD_DIR"/image.spec
else
  rpmbuild --target "$ARCH" -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/
