#!/bin/bash
set -e

build=true
version_suffix=$(git rev-parse --short HEAD)

while test $# -gt 0; do
  case "$1" in
    -h|--help)
      echo 'options:'
      echo '-h, --help          show help'
      echo '--no-prebuild       skip build and test'
      echo '--runtime           a valid RID (https://docs.microsoft.com/en-us/dotnet/core/rid-catalog)'
      echo '--version-suffix    version suffix for the binary. defaults to current git SHA'
      exit 0
      ;;
    --no-prebuild)
      build=false
      shift
      ;;
    --runtime*)
      shift
      runtime=$1
      shift
      ;;
    --version-suffix)
      shift
      version_suffix=$1
      shift
      ;;
    *)
      break
      ;;
  esac
done

if [ -z "$runtime" ]; then
    echo "error: no runtime specified; provide a valid RID (https://docs.microsoft.com/en-us/dotnet/core/rid-catalog)"
    exit 1
fi

if [ "$build" == true ]; then
    echo $'\n> bin/build\n'
    bin/build
else
    echo $'\nbuild skipped\n'
fi

cd src/slskd
echo $'\n> pwd\n'
pwd

echo $'\n> dotnet publish ... --runtime '$runtime$' --version-suffix '$version_suffix$'\n'
rm -rf dist/$runtime/*
dotnet publish \
    --configuration Release \
    -p:PublishSingleFile=true \
    -p:ReadyToRun=true \
    -p:PublishTrimmed=true \
    -p:IncludeNativeLibrariesForSelfExtract=true \
    -p:CopyOutputSymbolsToPublishDirectory=false \
    --self-contained \
    --version-suffix $version_suffix \
    --runtime $runtime \
    --output ../../dist/$runtime

echo $'\npublish succeeded.'