#!/bin/bash

if [ $1 = "beta" ]; then
   VERSION=`date '+%Y%m%d'`
else
   VERSION=`cat ../src/uVersion.pas | grep cVERSION`
   VERSION="$(echo -e "${VERSION}" | sed -e 's/^[[:space:]]*//')"
   VERSION="${VERSION:15:5}"
fi
mkdir ~/tmp/cqrlog_build_$VERSION -p
FINAL=~/tmp/cqrlog_build_$VERSION
#whre would you like to store final build files

function removeProperties {
    for f in `ls $1/src/*.lfm`;
    do
	echo $f
	sed -i '/PPI =/d' $f
	sed -i '/UseDollarString =/d' $f
    done
    echo "UseDollarString and PPI properties removed"
}


#****************************************
CTMP=`mktemp -d /tmp/tmp.XXXXXX`
platform=`uname -m`
REL=/tmp/cqrlog-$VERSION
case $platform in
"x86_64")
	ARCH=`echo "amd64"`
	;;
"armv7l")
	ARCH=`echo "armhf"`
	;;
*)
	ARCH=`echo "i386"`
	;;
esac
echo cqrlog_"$VERSION"_$ARCH.tar.gz
mkdir $CTMP/cqrlog-$VERSION -p
mkdir $FINAL -p
cd $CTMP
git clone git://github.com/ok2cqr/cqrlog.git cqrlog-$VERSION

# Raspbian still has old verison of Lazarus and FreePascal
# new properties from Lazarus 1.8 has to be removed
if [ "$ARCH" == "armhf" ];
then
    cd cqrlog-$VERSION
    removeProperties `pwd`
    cd ..
fi

if [ "$1" != "beta" ]; then
   tar -cvf cqrlog_$VERSION.orig.tar --exclude='debian' --exclude='.git' cqrlog-$VERSION
   gzip -v9 cqrlog_$VERSION.orig.tar
   cd cqrlog-$VERSION
   debuild -i -I -S
   dpkg-buildpackage -rfakeroot -i -I
   make clean
   cd ..
   tar -cvf cqrlog_$VERSION.deb.src.tar cqrlog*.orig.tar.gz cqrlog*.debian.tar.xz cqrlog*.changes cqrlog*.dsc
   gzip -v9 cqrlog_$VERSION.deb.src.tar

   pwd
   echo $FINAL
   ls -lh cqrlog*.deb
   ls -lh cqrlog*.deb.src.tar.gz
   cp cqrlog*.deb $FINAL
   cp cqrlog*.deb.src.tar.gz $FINAL
fi

cd cqrlog-$VERSION
make
make DESTDIR=$REL install
cd /tmp
tar cvzf cqrlog_"$VERSION"_$ARCH.tar.gz cqrlog-$VERSION
mv cqrlog_"$VERSION"_$ARCH.tar.gz $FINAL

