#!/bin/bash
set -e

prebuild=true

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 '--platform          one of: linux/amd64, linux/arm64, linux/arm/v7.  overrides runtime.'
      echo '--version           version for the binary. defaults to current git tag+SHA'
      echo '--output            the output directory.  defaults to ../../dist/<runtime>'
      exit 0
      ;;
    --no-prebuild)
      prebuild=false
      shift
      ;;
    --runtime*)
      shift
      runtime=$1
      shift
      ;;
    --platform*)
      shift
      platform=$1
      shift
      ;;
    --version)
      shift
      version=$1
      shift
      ;;
    --output)
      shift
      output=$1
      shift
      ;;
    *)
      break
      ;;
  esac
done

if [ ! -z "$platform" ]; then
  case "$platform" in
    linux/amd64)
      runtime="linux-x64"
      ;;
    linux/arm64)
      runtime="linux-arm64"
      ;;
    linux/arm/v7)
      runtime="linux-arm"
      ;;
    *)
      echo "💥  error: platform must be one of: linux/amd64, linux/arm64, linux/arm/v7"
      exit 1
      ;;
  esac

  echo $'\n\tℹ️  runtime overridden by platform option '$platform$', using '$runtime$'\n'
fi


if [ -z "$version" ]; then 
  tag=$(git describe --tags --abbrev=0)
  sha=$(git rev-parse --short HEAD)
  version=$tag+$sha
fi

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 [ -z "$output" ]; then
  output=$'../../dist/'$runtime
fi

if [ "$prebuild" == true ]; then
    echo $'\n\t🛠️  bin/build --version '$version$'\n'
    bin/build
else
    echo $'\n\t⏩  pre-build skipped\n'
fi

cd src/slskd
echo $'\n\t📍  '$(pwd)$'\n'

echo $'\n\t🛠️  dotnet publish ... --runtime '$runtime$' -p:Version '$version$' --output '$output$'\n'
rm -rf dist/$runtime/*

dotnet publish \
    --configuration Release \
    -p:PublishSingleFile=true \
    -p:ReadyToRun=true \
    -p:IncludeNativeLibrariesForSelfExtract=true \
    -p:CopyOutputSymbolsToPublishDirectory=false \
    -p:Version=$version \
    --self-contained \
    --runtime $runtime \
    --output $output

cd $output
echo $'\n\t📍  '$(pwd)$'\n'

echo $'\n\t📦  artifacts:\n'
ls -la .

echo $'\n\t🎉  publish succeeded!\n'