#!/bin/bash

set -e

# raise the limit on number of open files
ulimit -n 2048

PACKAGE_DIR=`pwd`

if [ "$1" != "Desktop" ] && [ "$1" != "Server" ]
then
   echo "error: must specify Desktop or Server as configuration"
   exit 1
fi

if [ "$2" != "DEB" ] && [ "$2" != "RPM" ]
then
   echo "error: must specify DEB or RPM as package target"
   exit 1
fi

# set build type( if necessary) and build dir
if test -z "$CMAKE_BUILD_TYPE"
then
   CMAKE_BUILD_TYPE=Release
   BUILD_DIR=build-$1-$2
else
   BUILD_DIR=build-$1-$2-$CMAKE_BUILD_TYPE
fi

# clean if requested
if [ "$3" == "clean" ]
then
   # remove existing build dir
   rm -rf $BUILD_DIR
   
   # clean out ant build
   cd ../../src/gwt
   ant clean
   cd $PACKAGE_DIR
fi

if [ "$1" == "Desktop" ]
then
  INSTALL_DIR=rstudio
else
  INSTALL_DIR=rstudio-server
fi

# build for SLES if requested
if [ "$4" == "SLES" ]
then
  RSTUDIO_PACKAGE_BUILD_SLES=1
fi

mkdir -p $BUILD_DIR
cd $BUILD_DIR
rm -f CMakeCache.txt
rm -rf $BUILD_DIR/_CPack_Packages
cmake -DRSTUDIO_TARGET=$1 \
      -DCMAKE_BUILD_TYPE=$CMAKE_BUILD_TYPE \
      -DRSTUDIO_PACKAGE_BUILD=1 \
      -DRSTUDIO_PACKAGE_BUILD_SLES=$RSTUDIO_PACKAGE_BUILD_SLES \
      -DCMAKE_INSTALL_PREFIX=/usr/lib/$INSTALL_DIR \
      ../../..

make

if [ "$2" != "DEB" ]
then
  fakeroot cpack -G $2
else
  cpack -G $2
  ../fix-debian-permissions `ls *.deb`
fi

cd ..
