#!/bin/bash

set -e

#Where source file of the debian package should be placed
SRC_DIR=debian/src

ROOT_DIR=`pwd`

#clean build directories
rm -rf $SRC_DIR debian/minerva-front*

#recreate directory
mkdir $SRC_DIR

export APP_PREFIX=/minerva
npm install
npm run build
cp -r out $SRC_DIR/front

cd $SRC_DIR
zip -r front.zip front
rm -r front
cd $ROOT_DIR

#copy changelog file
cp CHANGELOG $ROOT_DIR/debian/template/changelog

current_version=`cat CHANGELOG |grep minerva-front |head -1 | cut -f2 -d'(' | cut -f1 -d')'`

echo "Current version: " $current_version

#dh_make requires directory name to be like <package>-<version>
# this points to the directory
DEBIAN_DIR=debian/minerva-front-$current_version/

mkdir $DEBIAN_DIR

# copy all source files to this directory
cp $SRC_DIR/* $DEBIAN_DIR

#because dh_make works only from within directory where
#package data will be generated we need to change it
cd $DEBIAN_DIR
#this should be improved (to include src properly)
dh_make -s --createorig -e piotr.gawron@uni.lu -y -t $ROOT_DIR/debian/template

echo "1.0" > debian/source/format

#remove example files generated by dh_make
find -name '*.ex' ! -name 'minerva-front*' -type f -exec rm -f {} +

#set proper architecture
arch=`dpkg --print-architecture`
echo "Architecture: $arch" >>debian/control

#remove some sample file
rm debian/*.ex debian/README.Debian debian/README.source debian/minerva-front-docs.docs

#build debian package
debuild  --no-lintian -us -uc

#run separately to fail on errors
lintian --suppress-tags bad-distribution-in-changes-file --fail-on warning,error --no-tag-display-limit

# remove temporary changelog
rm $ROOT_DIR/debian/template/changelog
