#!/bin/zsh

### Setup OpenSSL
if [ "$(uname)" = "Darwin" ]; then
  echo "macOS"
  echo "Trying to import openssl"
  OPENSSL_PATH=/usr/local/opt/openssl@1.1/lib
  if test -d "$OPENSSL_PATH"; then
    export DYLD_LIBRARY_PATH=$OPENSSL_PATH
  else
    echo "OpenSSL not found"
    exit 100
  fi
elif [ "$(uname)" = "Linux" ]; then
  echo "Linux"
else
  echo "Unknown"
fi

### Running build script
if [ -z "$1" ]; then
  echo "Usage: $0 <version>"
  exit 1
fi

FILE_VERSION=$($1 | sed -r 's|^(([0-9]+).([0-9]+).([0-9]+))(.*)$|\1|')

sed -i "" -e "s|<AssemblyVersion>.*</AssemblyVersion>|<AssemblyVersion>$FILE_VERSION</AssemblyVersion>|" FitConnect/FitConnect.csproj
sed -i "" -e "s|<FileVersion>.*</FileVersion>|<FileVersion>$FILE_VERSION</FileVersion>|" FitConnect/FitConnect.csproj
sed -i "" -e "s|<PackageVersion>.*</PackageVersion>|<PackageVersion>$1</PackageVersion>|" FitConnect/FitConnect.csproj

dotnet clean

#if ! dotnet test -c Release; then
#  echo "Test failed"
#  exit 1
#fi

if ! dotnet build FitConnect -c Release; then
  echo "Build failed"
  exit 1
fi

if ! dotnet pack -c Release; then
  echo "Pack failed"
  exit 1
fi

cp "FitConnect/bin/Release/FitConnect.$1.nupkg" .

exit 0

#CURRENT=$(git branch | grep \* | cut -d ' ' -f2)
#if [ "$CURRENT" != "master" ]; then
#  echo "Not on master branch"
#  exit 1
#fi

# Here you can do the release things...
