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

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT_DIR"

VERSION="${VERSION:-0.2.0}"
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
GIT_HASH="$(git rev-parse --short HEAD 2>/dev/null || echo "unknown")"

echo "=> Building comic-odin v${VERSION} (${OS}-${ARCH})"
./build.sh

echo "=> Running test suite"
CLAY_DIR="$ROOT_DIR/vendor/clay/bindings/odin/clay-odin"
odin test tests -collection:clay="$CLAY_DIR"

mkdir -p dist
PKG_NAME="comic-odin-${VERSION}-${OS}-${ARCH}"
PKG_DIR="dist/${PKG_NAME}"

rm -rf "$PKG_DIR"
mkdir -p "$PKG_DIR"

# Binary
cp bin/comic_odin "$PKG_DIR/"

# Documentation
cp README.md "$PKG_DIR/"
cp docs/PORT_BACKLOG.md "$PKG_DIR/"
if [ -f CHANGELOG.md ]; then
  cp CHANGELOG.md "$PKG_DIR/"
fi

# Schemas
cp -r schemas "$PKG_DIR/"

# Version stamp file
cat > "$PKG_DIR/VERSION" <<EOF
version=${VERSION}
build_date=${BUILD_DATE}
git_hash=${GIT_HASH}
os=${OS}
arch=${ARCH}
EOF

# Package
TAR_PATH="dist/${PKG_NAME}.tar.gz"
rm -f "$TAR_PATH"
tar -czf "$TAR_PATH" -C dist "$PKG_NAME"

# Checksums
if command -v sha256sum >/dev/null 2>&1; then
  sha256sum "$TAR_PATH" > "${TAR_PATH}.sha256"
elif command -v shasum >/dev/null 2>&1; then
  shasum -a 256 "$TAR_PATH" > "${TAR_PATH}.sha256"
fi

echo ""
echo "=== Package Summary ==="
echo "Version:    ${VERSION}"
echo "Build date: ${BUILD_DATE}"
echo "Git hash:   ${GIT_HASH}"
echo "Package:    ${TAR_PATH}"
echo "Size:       $(du -h "$TAR_PATH" | cut -f1)"
echo "SHA256:     $(cat "${TAR_PATH}.sha256" | awk '{print $1}')"
echo ""
echo "Packaged: $TAR_PATH"
