#!/bin/bash

mk_tar() {
# mk-tar <upstream_name> <url> <tartype> <tar_name>
cd $wkdir
name=$1
url=$2
tartype=$3
pkgname=$4

maj=
min=
patch=
tweak=
version=
[[ -d git ]] || mkdir git
cd git
[[ -d $name ]] && rm -rf $name
git clone $url $name
cd ..
rm -rf $name && cp -rf git/$name/ .
cd $name

if [[ -f VERSION.cmake ]] ; then
maj=$(cat VERSION.cmake|grep "SET(PLUGIN_VERSION_MAJOR"|cut -d'"' -f2)
min=$(cat VERSION.cmake|grep "SET(PLUGIN_VERSION_MINOR"|cut -d'"' -f2)
patch=$(cat VERSION.cmake|grep "SET(PLUGIN_VERSION_PATCH"|cut -d'"' -f2)
tweak=$(cat VERSION.cmake|grep "SET(PLUGIN_VERSION_TWEAK"|cut -d'"' -f2)
fi

if [[ -z $maj ]] ; then
maj=$(cat VERSION.cmake|grep "(VERSION_MAJOR"|cut -d'"' -f2)
min=$(cat VERSION.cmake|grep "(VERSION_MINOR"|cut -d'"' -f2)
patch=$(cat VERSION.cmake|grep "(VERSION_PATCH"|cut -d'"' -f2)
tweak=$(cat VERSION.cmake|grep "(VERSION_TWEAK"|cut -d'"' -f2)
fi

if [[ -z $maj ]] ; then
maj=$(cat CMakeLists.txt|grep "(VERSION_MAJOR"|cut -d'"' -f2)
min=$(cat CMakeLists.txt|grep "(VERSION_MINOR"|cut -d'"' -f2)
patch=$(cat CMakeLists.txt|grep "(VERSION_PATCH"|cut -d'"' -f2)
tweak=$(cat CMakeLists.txt|grep "(VERSION_TWEAK"|cut -d'"' -f2)
fi

if [[ -z $maj ]] ; then
maj=$(grep -r "   PLUGIN_VERSION_MAJOR   "|rev|cut -d' ' -f1|rev)
min=$(grep -r "   PLUGIN_VERSION_MINOR   "|rev|cut -d' ' -f1|rev)
patch=$(grep -r "   PLUGIN_VERSION_PATCH   "|rev|cut -d' ' -f1|rev)
fi
version=$maj.$min.$patch.$tweak
if [[ -z $tweak ]]; then
version=$maj.$min.$patch
fi
if [[ -z $patch ]]; then
version=$maj.$min
fi

cd ..

case $tartype in
tar.gz)
opt=z
;;
tar.bz2)
opt=j
;;
tar.xz)
opt=J
;;
tar)
opt=
;;
*)
echo "Unsupported compression type"
exit 1
esac

echo "Please wait creating tarball..."
[[ -f $name-$version.$tartype ]] && rm $name-$version.$tartype
tar --exclude-vcs -c"$opt"f $name-$version.$tartype $name/
[[ $? = 0 ]] && chmod 644 $name-$version.$tartype && \
echo "Written $name-$version.$tartype"

rm -rf $name
# Clear vars created by this fn
pkgname=
name=
url=
tartype=
maj=
min=
patch=
tweak=
version=
opt=
chkflag=
}

# Main routine -----------
# Check we are in SOURCES
[[ $(pwd|rev|cut -d/ -f1|rev) = "SOURCES" ]] || { echo "Not in SOURCES directory - aborting!"; exit 1; }
wkdir=$(pwd)
rm -rf git
mk_tar oernc_pi https://github.com/bdbcat/oernc_pi/ tar.gz opencpn-oernc-plugin
rm -rf git 
