#!/usr/bin/env bash
set -euo pipefail

version="${1:?Usage: publish-platform-packages.sh <version> [output-dir] [default|all]}"
output_dir="${2:-artifacts/packages}"
profile="${3:-default}"

case "$profile" in
  default)
    runtimes=(win-x64 linux-x64 linux-arm64)
    ;;
  all)
    runtimes=(win-x64 win-arm64 linux-x64 linux-arm64 osx-x64 osx-arm64)
    ;;
  *)
    echo "Unknown platform profile: $profile" >&2
    exit 2
    ;;
esac

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repository_root="$(cd "$script_dir/.." && pwd)"
project="$repository_root/src/Jiaowu.Api/Jiaowu.Api.csproj"

mkdir -p "$output_dir"
output_dir="$(cd "$output_dir" && pwd)"
if find "$output_dir" -mindepth 1 -maxdepth 1 -print -quit | grep -q .; then
  echo "Output directory must be empty: $output_dir" >&2
  exit 2
fi

temporary_root="$(mktemp -d)"
trap 'rm -rf "$temporary_root"' EXIT

for runtime in "${runtimes[@]}"; do
  package_name="jiaowu-${version}-${runtime}"
  package_root="$temporary_root/$package_name"

  dotnet publish "$project" \
    --configuration Release \
    --runtime "$runtime" \
    --self-contained false \
    --output "$package_root" \
    -p:BuildFrontendOnPublish=false \
    -p:Version="$version" \
    -p:DebugSymbols=false \
    -p:DebugType=None \
    -p:PublishReadyToRun=false

  cp "$repository_root/.env.example" "$package_root/.env.example"
  cp "$repository_root/README.md" "$package_root/README.md"

  if [[ "$runtime" == win-* ]]; then
    (
      cd "$temporary_root"
      zip -q -r "$output_dir/$package_name.zip" "$package_name"
    )
  else
    tar -C "$temporary_root" -czf "$output_dir/$package_name.tar.gz" "$package_name"
  fi

  rm -rf "$package_root"
done

(
  cd "$output_dir"
  find . -maxdepth 1 -type f \
    \( -name '*.zip' -o -name '*.tar.gz' \) \
    -printf '%f\n' |
    sort |
    xargs sha256sum > SHA256SUMS
)
