#!/bin/bash
# Build script for Linux release binary and create application package

set -e

echo "Building Markus for Linux..."

# Navigate to project root
cd "$(dirname "$0")/.."

# Clean previous builds
echo "Cleaning previous builds..."
dotnet clean MarkdownEditor.csproj -c Release

# Build for Linux x64
echo "Building for Linux x64..."
dotnet publish MarkdownEditor.csproj \
    -c Release \
    -r linux-x64 \
    --self-contained true \
    -p:PublishSingleFile=true \
    -p:IncludeNativeLibrariesForSelfExtract=true \
    -o ./bin/Release/linux-x64/publish

# Create application directory structure
APP_DIR="./bin/Release/linux-x64/OrmentiaMarkus"
echo "Creating application package..."
rm -rf "$APP_DIR"
mkdir -p "$APP_DIR"
mkdir -p "$APP_DIR/bin"
mkdir -p "$APP_DIR/share/applications"
mkdir -p "$APP_DIR/share/icons/hicolor/256x256/apps"

# Copy executable
cp ./bin/Release/linux-x64/publish/OrmentiaMarkus "$APP_DIR/bin/"
chmod +x "$APP_DIR/bin/OrmentiaMarkus"

# Copy icon
if [ -f "Assets/AppIcon.iconset/icon_256x256.png" ]; then
    cp "Assets/AppIcon.iconset/icon_256x256.png" "$APP_DIR/share/icons/hicolor/256x256/apps/ormentia-markus.png"
fi

# Create .desktop file
cat > "$APP_DIR/share/applications/ormentia-markus.desktop" << EOF
[Desktop Entry]
Version=1.0
Type=Application
Name=Markus
Comment=A Simple Markdown Editor
Exec=OrmentiaMarkus
Icon=ormentia-markus
Categories=Office;TextEditor;Utility;
Terminal=false
StartupNotify=true
EOF

# Create launcher script
cat > "$APP_DIR/OrmentiaMarkus" << 'EOF'
#!/bin/bash
# Launcher script for Markus
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
exec "$SCRIPT_DIR/bin/OrmentiaMarkus" "$@"
EOF
chmod +x "$APP_DIR/OrmentiaMarkus"

# Create README
cat > "$APP_DIR/README.txt" << EOF
Markus - A Simple Markdown Editor
==================================

Installation:
1. Extract this archive to your preferred location (e.g., /opt or ~/Applications)
2. Run ./OrmentiaMarkus to launch the application
3. (Optional) Copy share/applications/ormentia-markus.desktop to ~/.local/share/applications/ 
   for desktop menu integration

© 2025 Ormentia. All rights reserved.
https://ormentia.com
EOF

# Clean up publish directory
rm -rf ./bin/Release/linux-x64/publish

echo ""
echo "✓ Build completed successfully!"
echo "Application package: ./bin/Release/linux-x64/OrmentiaMarkus/"
echo ""
echo "You can now:"
echo "  1. Run ./bin/Release/linux-x64/OrmentiaMarkus/OrmentiaMarkus"
echo "  2. Archive and distribute the OrmentiaMarkus folder"
echo "  3. Install to /opt or ~/Applications"
echo ""

