#!/bin/sh
#
# The ESO pipeline packages come in the form of a "kit" containing all
# packages needed to build the pipeline. This also includes some non-free
# packages like Gasgano.
# To allow the pipelines to be put to Debian "main", and to have a more 
# convienient build process, we extract just the source package.
#
# Debian package name ("cpl-plugin-fors")
DEBIAN_PACKAGE=$(echo $(basename $3) | cut -d_ -f1)

# Pipeline name ("fors")
PIPELINE=$(echo ${DEBIAN_PACKAGE} | cut -d- -f3-)

# Version number ("4.9.4")
VERSION=$2

# Include full calibration set?
# If not, the "calib" package will act as a "downloader" package for the 
# calibration files.
INCLUDE_CALIB="no"
#INCLUDE_CALIB="yes"

# Include test data?
# If not, the test (fits) data are removed from the source package.
# In this case, also the tests need to be adjusted.
#INCLUDE_TEST_DATA="no"
INCLUDE_TEST_DATA="yes"

BASEDIR=$(dirname $3)
FILENAME=${BASEDIR}/${PIPELINE}-kit-${VERSION}.tar.gz
if [ ! -f ${FILENAME} ] ; then
  FILENAME=${BASEDIR}/${PIPELINE}-kit-${VERSION}-*.tar.gz
  UVERSION=$(echo ${FILENAME} | sed "s/.*-kit-\(.*\)\.tar.gz/\1/")
else
  UVERSION=${VERSION}
fi
tar xf ${FILENAME} -C ${BASEDIR}
rm -f ${BASEDIR}/${DEBIAN_PACKAGE}_${UVERSION}.orig*.tar.* ${FILENAME}

TAREXCLUDE="--exclude ${PIPELINE}-${VERSION}/html"
if [ $INCLUDE_TEST_DATA = "no" ] ; then
  TAREXCLUDE=${TAREXCLUDE}" --exclude ${PIPELINE}-${VERSION}/*/tests/ref_data"
fi

tar xf ${BASEDIR}/${PIPELINE}-kit-${UVERSION}/${PIPELINE}-${VERSION}.tar.gz\
    -C ${BASEDIR} ${TAREXCLUDE}
tar xf ${BASEDIR}/${PIPELINE}-kit-${UVERSION}/${PIPELINE}-calib-${VERSION}.tar.gz\
    -C ${BASEDIR}/${PIPELINE}-${VERSION}/
mv ${BASEDIR}/${PIPELINE}-${VERSION}/${PIPELINE}-calib-${VERSION}/ \
   ${BASEDIR}/${PIPELINE}-${VERSION}/calib/
if [ $INCLUDE_CALIB = "no" ] ; then
  du -s ${BASEDIR}/${PIPELINE}-${VERSION}/calib/cal | cut -f1 \
      > ${BASEDIR}/${PIPELINE}-${VERSION}/calib/cal_size
  rm -rf ${BASEDIR}/${PIPELINE}-${VERSION}/calib/cal
fi

tar cJf ${BASEDIR}/${DEBIAN_PACKAGE}_${VERSION}+dfsg.orig.tar.xz \
    -C ${BASEDIR} ${PIPELINE}-${VERSION}/
rm -rf ${BASEDIR}/${PIPELINE}-${VERSION}/

rm -rf ${BASEDIR}/${PIPELINE}-kit-${UVERSION}/ 

#exec uupdate --no-symlink --upstream-version ${VERSION}+dfsg \
#     ${BASEDIR}/${DEBIAN_PACKAGE}_${VERSION}+dfsg.orig.tar.xz
