#!/bin/bash
set -e

# Zinit Build Script
# Builds zinit (client) and zinit-server for current platform and installs to ~/hero/bin/
# On Linux, also builds zinit-pid1

INSTALL_DIR="$HOME/hero/bin"

# Extract version from Cargo.toml
VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')

echo "=== Zinit Build Script ==="
echo "Version: $VERSION"
echo "Platform: $(uname -s)"
echo "Install dir: $INSTALL_DIR"
echo ""
echo "Building zinit and zinit-server..."

# Run main tests
cargo test --lib --features full

# Build release (excludes zinit-pid1 on non-Linux)
cargo build --release --features full

# Create install directory
mkdir -p "$INSTALL_DIR"

# Remove old binaries
rm -f "$INSTALL_DIR/zinit"
rm -f "$INSTALL_DIR/zinit-server"
rm -f "$INSTALL_DIR/zinit-pid1"

# Copy binaries
cp target/release/zinit "$INSTALL_DIR/"
cp target/release/zinit-server "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR/zinit"
chmod +x "$INSTALL_DIR/zinit-server"

echo "Installed to $INSTALL_DIR:"
echo "  - zinit (client)"
echo "  - zinit-server (daemon)"

# On Linux, also install zinit-pid1
if [[ "$(uname)" == "Linux" ]]; then
    # Build zinit-pid1 explicitly (not in default-members)
    cargo build --release -p zinit-pid1
    cp target/release/zinit-pid1 "$INSTALL_DIR/"
    chmod +x "$INSTALL_DIR/zinit-pid1"
    echo "  - zinit-pid1 (init process)"
fi

# Check if ~/hero/bin is in PATH
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    echo ""
    echo "NOTE: Add $INSTALL_DIR to your PATH:"
    echo "  export PATH=\"\$HOME/hero/bin:\$PATH\""
    echo ""
    echo "Add this to your ~/.bashrc or ~/.zshrc"
fi

echo ""
echo "Usage:"
echo "  zinit-server            # Start server (foreground)"
echo "  zinit list              # List services"
echo "  zinit status <name>     # Show service status"
echo "  zinit start <name>      # Start a service"
echo "  zinit stop <name>       # Stop a service"
echo "  zinit repl              # Interactive REPL"
echo "  zinit tui               # Full-screen TUI"
