#!/usr/bin/env bash

set -euo pipefail

version="${1:?Usage: publish-platform-packages.sh <version> [output-directory] [default|all]}"
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repository_root="$(cd "${script_dir}/.." && pwd)"
output_directory="${2:-${repository_root}/artifacts/packages}"
platform_profile="${3:-default}"
web_project="${repository_root}/src/Eis.Web/Eis.Web.csproj"
tools_project="${repository_root}/src/Eis.Tools/Eis.Tools.csproj"

case "${platform_profile}" in
  default)
    runtime_identifiers=(win-x64 linux-x64 linux-arm64)
    ;;
  all)
    runtime_identifiers=(win-x64 win-arm64 linux-x64 linux-arm64 osx-x64 osx-arm64)
    ;;
  *)
    echo "Unknown platform profile: ${platform_profile}. Expected default or all." >&2
    exit 2
    ;;
esac

if [[ "${output_directory}" != /* ]]; then
  output_directory="${repository_root}/${output_directory}"
fi
mkdir -p "${output_directory}"
output_directory="$(cd "${output_directory}" && pwd)"
temporary_root="$(mktemp -d)"
trap 'rm -rf "${temporary_root}"' EXIT

for runtime_identifier in "${runtime_identifiers[@]}"; do
  package_name="eis-${version}-${runtime_identifier}"
  package_root="${temporary_root}/${package_name}"
  application_root="${package_root}/app"

  echo "Publishing ${package_name}..."
  dotnet publish "${web_project}" \
    --configuration Release \
    --runtime "${runtime_identifier}" \
    --self-contained true \
    --output "${application_root}" \
    -p:Version="${version}"

  dotnet publish "${tools_project}" \
    --configuration Release \
    --runtime "${runtime_identifier}" \
    --self-contained true \
    --output "${application_root}" \
    -p:Version="${version}"

  cp "${repository_root}/README.md" "${package_root}/README.md"
  cp "${repository_root}/LICENSE" "${package_root}/LICENSE"
  cp "${repository_root}/.env.example" "${package_root}/.env.example"

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

  rm -rf "${package_root}"
done

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

echo "Platform packages were written to ${output_directory}"
