#!/bin/bash

# A wrapper around the patched qmake.bin binary
# This demonstrates how specialised code generators can get created
FILE=""

while test $# -gt 0; do
  case $1 in
    *-file)
      FILE="$2"
      shift
    ;;
    *-outdir)
      OUTDIR="$2"
      shift
    ;;
    *)
      echo Unknown parameter $1.
      echo 'Usage: generator_qmake [--file $FILE] --outdir $OUT'
      exit 1
    ;;
  esac
  shift
done

if [ -z "$OUTDIR" ]; then
  echo "ERROR: no output directory is given via --outdir parameter!"
  exit 1
fi

[ -z "$TMPDIR" ] && TMPDIR="/tmp/"
TEMPDIR="$TMPDIR/generator.qmake.$$"
mkdir -p "$TEMPDIR"
if [ -z "$FILE" ]; then
  # not defined, just pick the first tar ball
  FILE=`find . -name \*.tar.gz -o -name \*.tar.bz2|head -n 1`
  if [ -z "$FILE" ]; then
    # not defined, just pick the first tar ball
    FILE=`find . -name \*.zip |head -n 1`
    if [ -z "$FILE" ]; then
      echo "ERROR: No tar ball found, nor specified"
      exit 1
    fi
  fi
fi

if [ "${FILE%.zip}" != "$FILE" ] ; then
  unzip -q "$FILE" -d "$TEMPDIR"
else
  tar xf "$FILE" -C "$TEMPDIR" || exit 1
fi
cd "$TEMPDIR"/* || exit 1
tarpath="${PWD##*/}"
find "$TEMPDIR"/* -name \*.spec | while read i; do rm "$i" ; done

# run the code generator
export QMAKESPEC=/usr/share/qt4/mkspecs/linux-g++
# first try just toplevel
/usr/lib/obs/service/qmake.bin PREFIX=/usr
spec=`find "$TEMPDIR"/* -name \*.spec|head -n 1`
if [ -z "$spec" -o ! -f "$spec" ]; then
  # no success, try with subdirs
  if ! /usr/lib/obs/service/qmake.bin -r PREFIX=/usr; then
    cd -
    rm -rf "$TEMPDIR"
    exit 1
  fi
fi
cd -


# and move created spec file into outdir
mkdir -p "$OUTDIR"
FILENAME="${FILE##*:}"
# single file hit ?
specfiles=`find "$TEMPDIR"/* -name ${FILENAME%%-*}.spec`
if [ -z "$specfiles" ]; then 
  specfiles=`find "$TEMPDIR"/* -name ${FILENAME%%-*}\*.spec`
  if [ -z "$specfiles" ]; then 
    specfiles=`find "$TEMPDIR"/* -name \*.spec`
  fi
fi
for file in $specfiles; do 
  # Fix the source tar ball name, qmake generator can know it
  sed -i -e 's/^Source:.*/Source: '"${FILE##*[:/]}"'/' "$file"

  # Fix the version if set to default value, in many cases 
  # it is not specified in .pro file
  path="${FILE%.tar.bz2}"
  path="${path%.tar.gz}"
  path="${path%.zip}"
  path="${path##*:}"
  version="${path##*-}"
  sed -i -e 's/^Version: 1.0.0.*/Version: '"${version}"'/' \
         -e 's/^%setup .*/%setup -q -n '"$tarpath"'/' "$file"
  mv "$file" "$OUTDIR/"
done

#cleanup
cd -
rm -rf "$TEMPDIR"

# success !
exit 0
