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

usage() {
  echo "Usage: $0 --linux PATH --windows PATH" >&2
  exit 2
}

linux_binary=
windows_binary=
while (($#)); do
  case "$1" in
    --linux) linux_binary=${2:-}; shift 2 ;;
    --windows) windows_binary=${2:-}; shift 2 ;;
    *) usage ;;
  esac
done

[[ -n "$linux_binary" && -f "$linux_binary" ]] || usage
[[ -n "$windows_binary" && -f "$windows_binary" ]] || usage

version=$(awk -F '"' '$1 ~ /^version = / { print $2; exit }' Cargo.toml)
[[ -n "$version" ]] || { echo "Could not read the package version." >&2; exit 1; }

dist=dist
stage=$(mktemp -d)
repository_root=$PWD
trap 'rm -rf "$stage"' EXIT
rm -rf "$dist"
mkdir -p "$dist"

package_tarball() {
  local platform=$1 binary=$2
  local root="mudmouth-v${version}-${platform}"
  mkdir -p "$stage/$root"
  cp "$binary" "$stage/$root/mudmouth"
  cp README.md LICENSE config.toml "$stage/$root/"
  tar -C "$stage" -czf "$dist/$root.tar.gz" "$root"
  rm -rf "$stage/$root"
}

package_tarball x86_64-unknown-linux-gnu "$linux_binary"
windows_root="mudmouth-v${version}-x86_64-pc-windows-gnu"
mkdir -p "$stage/$windows_root"
cp "$windows_binary" "$stage/$windows_root/mudmouth.exe"
cp README.md LICENSE config.toml "$stage/$windows_root/"
(
  cd "$stage"
  zip -q -r "$repository_root/$dist/${windows_root}.zip" "$windows_root"
)

(
  cd "$dist"
  sha256sum -- *.tar.gz *.zip > SHA256SUMS.txt
)

printf 'Created release assets in %s:\n' "$dist"
cat "$dist/SHA256SUMS.txt"
