#!/bin/bash

# ============================================
# MindOS Desktop - Linux Build Script
# Usage: ./scripts/build-linux.sh [--mac-zip]
# Output: dist/*.AppImage, dist/*.deb (default)
#         dist/*.zip (with --mac-zip, cross-compile unsigned macOS zip)
# ============================================

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
REPO_ROOT="$(dirname "$PROJECT_DIR")"

cd "$PROJECT_DIR"

MAC_ZIP=false
while [[ $# -gt 0 ]]; do
    case $1 in
        --mac-zip)  MAC_ZIP=true; shift ;;
        --help|-h)
            echo "Usage: ./scripts/build-linux.sh [--mac-zip]"
            echo ""
            echo "Options:"
            echo "  --mac-zip    Cross-compile unsigned macOS zip (instead of Linux packages)"
            echo "  -h, --help   Show this help message"
            exit 0
            ;;
        *) echo "Unknown option: $1"; exit 1 ;;
    esac
done

# Install dependencies
echo -e "\n${YELLOW}Installing dependencies...${NC}"
cd "$REPO_ROOT"
pnpm install --no-frozen-lockfile

# Build Next.js standalone
echo -e "\n${YELLOW}Building Next.js standalone...${NC}"
cd "$REPO_ROOT"
pnpm --filter @geminilight/mindos build
pnpm --filter @mindos/web build

# Build Electron
echo -e "\n${YELLOW}Building Electron...${NC}"
cd "$PROJECT_DIR"
pnpm run build

# Package
if [ "$MAC_ZIP" = true ]; then
    echo -e "\n${YELLOW}Building macOS zip (unsigned, cross-compile from Linux)...${NC}"
    # One prepare+build cycle per arch: the bundled Node in resources/ must
    # match BOTH the target platform (darwin — not this Linux host!) and the
    # arch being packed, since electron-builder copies the same extraResources
    # dir into every package it produces.
    for ARCH in x64 arm64; do
        echo -e "\n${YELLOW}Preparing darwin-${ARCH} runtime...${NC}"
        MINDOS_BUNDLE_NODE_PLATFORM=darwin MINDOS_BUNDLE_NODE_ARCH="$ARCH" pnpm run prepare-mindos-runtime
        CSC_IDENTITY_AUTO_DISCOVERY=false pnpm exec electron-builder --mac zip "--$ARCH" --publish never
    done
    echo -e "\n${GREEN}Done!${NC}"
    ls -lh dist/*.zip 2>/dev/null
    echo -e "\n${YELLOW}These builds are UNSIGNED. Users need: xattr -cr /Applications/MindOS.app${NC}"
else
    echo -e "\n${YELLOW}Preparing bundled runtime...${NC}"
    pnpm run prepare-mindos-runtime
    echo -e "\n${YELLOW}Building Linux packages...${NC}"
    pnpm exec electron-builder --linux --publish never
    echo -e "\n${GREEN}Done!${NC}"
    ls -lh dist/*.AppImage dist/*.deb 2>/dev/null
fi
