#!/bin/bash

# $1 - Project directory (required).
# $2 - Project (required).
# $3 - Version (required).
# $4 - Distribution (required).
# $5 - Architecture (required).

if [ "$#" -ne "5" ]; then
  if [ "$#" -lt "5" ]; then
    echo "Error: missing parameters."
  else
    echo "Error: extra parameters."
  fi

  echo "Usage: $0 [projectdir] [projectname] [projectversion] [distribution] [x86 | x86_64]"
  exit 1
fi

# Make script easier to read.
ProjDir="$1"
Project="$2"
Version="$3"
Dist="$4"
Arch="$5"

if [ "$Arch" == "x86" ]; then
  BArch="i386"
  TArch="i686"
elif [ "$Arch" == "x86_64" ]; then
  BArch="x86_64"
  TArch="x86_64"
else
  echo "Error: invalid architecture (use 'x86' or 'x86_64')."
  exit 1
fi

# Create Fedora package.
tar xzf "${Project}-${Version}.tar.gz" &&
cd "${Project}-${Version}" &&
mock --buildsrpm --offline -r fedora-${Dist}-${BArch} --spec "redhat/${Project}.spec" --sources "../${Project}-${Version}.tar.gz" &&
mv "/var/lib/mock/fedora-${Dist}-${BArch}/result/${Project}-${Version}"-?.fc${Dist}.src.rpm .. &&
mock --rebuild --offline -r fedora-${Dist}-${BArch} "../${Project}-${Version}"-?.fc${Dist}.src.rpm &&
mv "/var/lib/mock/fedora-${Dist}-${BArch}/root/builddir/build/SRPMS/${Project}-${Version}"-?.fc${Dist}.src.rpm "${ProjDir}" &&
mv "/var/lib/mock/fedora-${Dist}-${BArch}/root/builddir/build/RPMS/${Project}-qt-${Version}"-?.fc${Dist}.${TArch}.rpm "${ProjDir}" &&
chmod go+w,o+t /tmp &&
su builder -c "rpmlint -i ${ProjDir}/${Project}-${Version}-?.fc${Dist}.src.rpm" &&
su builder -c "rpmlint -i ${ProjDir}/${Project}-qt-${Version}-?.fc${Dist}.${TArch}.rpm" &&
cd "${ProjDir}"
