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

cd "$(dirname "$0")/.."

if ! command -v zip >/dev/null 2>&1; then
  echo "zip command not found. Install zip and try again."
  exit 1
fi

if [ "${REBUILD_BUNDLE:-0}" = "1" ]; then
  ./scripts/build_pyinstaller_bundle.sh
fi

BUNDLE_DIR="dist/ATHENODE-desktop"
if [ ! -d "${BUNDLE_DIR}" ]; then
  echo "Desktop bundle not found at ${BUNDLE_DIR}."
  echo "Run ./scripts/build_pyinstaller_bundle.sh first (or set REBUILD_BUNDLE=1)."
  exit 1
fi

STAMP="$(date +%Y%m%d_%H%M%S)"
OS_NAME="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH_NAME="$(uname -m | tr '[:upper:]' '[:lower:]')"
PACKAGE_NAME="${1:-athenode_desktop_${OS_NAME}_${ARCH_NAME}_${STAMP}}"
ZIP_PATH="dist/${PACKAGE_NAME}.zip"

STAGE_DIR="$(mktemp -d)"
cleanup() {
  rm -rf "${STAGE_DIR}"
}
trap cleanup EXIT

cp -R "${BUNDLE_DIR}" "${STAGE_DIR}/ATHENODE-desktop"

(
  cd "${STAGE_DIR}"
  zip -qr "${OLDPWD}/${ZIP_PATH}" "ATHENODE-desktop"
)

if command -v shasum >/dev/null 2>&1; then
  shasum -a 256 "${ZIP_PATH}" > "${ZIP_PATH}.sha256"
fi

echo "Created desktop release zip: ${ZIP_PATH}"
if [ -f "${ZIP_PATH}.sha256" ]; then
  echo "Created checksum: ${ZIP_PATH}.sha256"
fi
