#!/bin/sh
set -e

# Install tools (Alpine container)
apk add --no-cache curl zip

echo "------------------------------------------------"
echo "Publishing Packages for Version: $VERSION"
echo "------------------------------------------------"

# --- 1. WINDOWS EDITOR ---
echo "Packaging Windows Editor..."
zip -j godot-editor-windows.zip dist/godot-windows-editor/*.exe

curl --fail --user "$ACTOR:$TOKEN" \
  --upload-file "godot-editor-windows.zip" \
  "$API_URL/godot-editor-windows/$VERSION/godot-editor-windows.zip"

# --- 2. LINUX EDITOR ---
echo "Packaging Linux Editor..."
# Find the linux binary (it has no extension, so we grep for 'godot.')
LINUX_BIN=$(find dist/godot-linux-editor -type f -name "godot.linuxbsd.editor*" | head -n 1)
zip -j godot-editor-linux.zip "$LINUX_BIN"

curl --fail --user "$ACTOR:$TOKEN" \
  --upload-file "godot-editor-linux.zip" \
  "$API_URL/godot-editor-linux/$VERSION/godot-editor-linux.zip"

# --- 3. EXPORT TEMPLATES (Windows + Linux) ---
echo "Packaging Templates (.tpz)..."
mkdir -p templates

# Windows Templates (Filter out console wrapper)
cp $(ls dist/godot-windows-debug/*.exe | grep -v "console") templates/windows_debug_x86_64.exe
cp $(ls dist/godot-windows-release/*.exe | grep -v "console") templates/windows_release_x86_64.exe

# Linux Templates
cp $(find dist/godot-linux-debug -type f -name "godot.*") templates/linux_debug.x86_64
cp $(find dist/godot-linux-release -type f -name "godot.*") templates/linux_release.x86_64

# Create TPZ
zip -j templates.tpz templates/*

curl --fail --user "$ACTOR:$TOKEN" \
  --upload-file "templates.tpz" \
  "$API_URL/godot-templates/$VERSION/templates.tpz"

echo "✅ All packages published successfully!"