#!/bin/bash
export SDKARTIFACTS=lib3mf_sdk

if [ -n "$1" ]; then
	export LOCATION="$1"
else
	export LOCATION="remote"
fi

if [ -n "$2" ]; then
	export OUTFILE=$2
else
	export OUTFILE="lib3mf_sdk.zip"
fi

function failed {
  echo "$1" 1>&2
  exit 1;
}

echo Clean artifacts-folder $SDKARTIFACTS
rm -rf $SDKARTIFACTS
mkdir $SDKARTIFACTS

echo Copy License, Readme, Examples and Bindings
cat ../LICENSE > $SDKARTIFACTS/License.txt & cat Credits.txt >> $SDKARTIFACTS/License.txt
cp -r Readme.md $SDKARTIFACTS
cp -r Examples $SDKARTIFACTS/Examples
cp -r ../Autogenerated/Bindings $SDKARTIFACTS

# download from readthedocs or build locally using sphinx
# cp ../Lib3MF-1.pdf $SDKARTIFACTS/Doc/.

echo Obtain binaries
mkdir -p $SDKARTIFACTS/Bin || failed "Error creating Bin-folder"
mkdir -p $SDKARTIFACTS/Lib || failed "Error creating Lib-folder"

function obtainlibrarycmd {
  if [ "$LOCATION" == "remote" ]; then
	  echo curl -s --retry 5 -m90 ${BUILDSERVER}/artifact/artifacts/lib3mf_$1.$2 -o $SDKARTIFACTS/$3/lib3mf.$2 || failed "Error obtaining latest lib3mf.$2"
	  curl -s --retry 5 -m90 ${BUILDSERVER}/artifact/artifacts/lib3mf_$1.$2 -o $SDKARTIFACTS/$3/lib3mf.$2 || failed "Error obtaining latest lib3mf.$2"
	  FS=`stat --printf="%s" $SDKARTIFACTS/$3/lib3mf.$2`
	  if [ "$FS" -lt "1000" ]; then
		failed "Error obtaining latest lib3mf.$2. File size too small."
	  fi
  else
    cp $LOCATION/lib3mf_$1.$2 $SDKARTIFACTS/$3/lib3mf.$2 || failed "Error obtaining latest lib3mf.$2"
  fi
}

obtainlibrarycmd "linux64" "so" "Bin"
obtainlibrarycmd "win64" "dll" "Bin"
obtainlibrarycmd "darwin" "dylib" "Bin"
obtainlibrarycmd "win64" "lib" "Lib"

echo Generate version.txt
VERSIONTXT="$SDKARTIFACTS/version.txt"
echo VERSIONTXT = $VERSIONTXT
echo "[Lib3MF_SDK]" > $VERSIONTXT
echo "BuildNumber = "$BUILD_NUMBER >> $VERSIONTXT
if [ -n "${GIT_BRANCH#*/}" ]; then
	echo "GITBranch = ${GIT_BRANCH#*/}" >> $VERSIONTXT
else
	echo "GITBranch = "`git rev-parse --abbrev-ref HEAD` >> $VERSIONTXT
fi
echo "GITRevision = "`git rev-parse HEAD` >> $VERSIONTXT

echo Zip SDK artifacts
zip -r $OUTFILE $SDKARTIFACTS/* || failed "Error zipping SDK"
