#!/bin/bash

# Super simple wrapper just to run over all prodct files

if [ "$1" != "--outdir" -o ! -d "$2" ]; then
  echo "no directory specified via --outdir parameter"
  exit 1
fi
outdir="$2"

# Ugly hack to workaround evil wrapper scripts
if [ -z "$OBS_NAME" ]; then
  if [ -x /usr/bin/osc ]; then
    echo
    echo "WARNING: OBS_NAME not set, trying request the server via osc ..."
    export OBS_NAME=`osc api /configuration | sed -n 's,.*<name>\(.*\)</name>.*,\1,p'`
    echo "         We got $OBS_NAME as return"
    echo
  fi
fi

if [ -z "$OBS_NAME" ]; then
  echo "WARNING: OBS_NAME not set, identifiers will not match with server config!"
  echo "         This is fine for debugging, but not for production media!"
fi

if [ -n "$OSC_VERSION" ]; then
  echo
  echo "WARNING"
  echo "WARNING Manual run using osc is *NOT* updating existing release spec files!"
  echo "WARNING"
  echo
fi

# create all build descriptions
for file in *.product; do
  if [ ! -r "$file" ]; then
    echo "ERROR: $file is not readable"
    exit 1
  fi
  ${0%/*}/create_single_product "$PWD/$file" "$outdir" "$OBS_SERVICE_PROJECT" || exit 1
done

# create _multibuild, except user provided one already
if [ -e "_multibuild" ]; then
  echo "SKIPPING _multibuild generation due to provided file"
  exit 0
fi

echo "<multibuild>" > "$outdir/_multibuild"
for file in "$outdir"/*.spec "$outdir/"*.kiwi; do
  if [ ! -e "$file" ]; then
    echo "File not readable: $i"
    exit 1
  fi
  container="${file##*/}"
  container="${container%.kiwi}"
  container="${container%.spec}"
  echo "  <package>${container}</package>" >> "$outdir/_multibuild"
done
echo "</multibuild>" >> "$outdir/_multibuild"

exit 0
