#!/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
  RealArch="i386"
elif [ "$Arch" == "x86_64" ]; then
  RealArch="amd64"
else
  echo "Error: invalid architecture (use 'x86' or 'x86_64')."
  exit 1
fi

# Create Debian package.
cp "${Project}-${Version}.tar.gz" "../${Project}_${Version}.orig.tar.gz" &&
cd .. &&
tar xzf "${Project}_${Version}.orig.tar.gz" &&
cd "${Project}-${Version}" &&
dpkg-buildpackage -uc -us -S &&
pbuilder build --basetgz "/${Dist}-${RealArch}.tgz"  \
    "../${Project}_${Version}"-?.dsc &&
su builder -c "lintian -i --color auto --pedantic \
    /var/cache/pbuilder/result/${Project}_${Version}-?.dsc" &&
su builder -c "lintian -i --color auto --pedantic \
    /var/cache/pbuilder/result/${Project}-qt_${Version}-?_${RealArch}.deb" &&
cp "/var/cache/pbuilder/result/${Project}_${Version}"-?.dsc "${ProjDir}" &&
cp "/var/cache/pbuilder/result/${Project}-qt_${Version}"-?_"${RealArch}.deb" \
    "${ProjDir}" &&
cd "${ProjDir}"
