#!/bin/bash
set -e

echo "🚀 Installing Cortex Agent Daemon from Bundle..."

# Determine OS
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"

# 1. Create .cortex/agent-node directory
INSTALL_DIR="$HOME/.cortex/agent-node"
mkdir -p "$INSTALL_DIR"

# 2. Copy binary and config into installation directory
cp cortex-agent "$INSTALL_DIR/cortex-agent"
cp agent_config.yaml "$HOME/.cortex/agent.yaml"
chmod +x "$INSTALL_DIR/cortex-agent"

if [ "$OS" = "darwin" ]; then
    # Bypass Apple Gatekeeper quarantine for internet-downloaded binaries
    xattr -c "$INSTALL_DIR/cortex-agent" 2>/dev/null || true
fi

# 3. Bootstrap daemon installation
echo "[*] Bootstrapping agent background daemon..."

if [ "$OS" = "darwin" ]; then
    echo "Installing macOS launchd service..."
    AGENTS_DIR="$HOME/Library/LaunchAgents"
    mkdir -p "$AGENTS_DIR"
    PLIST_PATH="$AGENTS_DIR/com.jerxie.cortex.agent.plist"
    cat > "$PLIST_PATH" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.jerxie.cortex.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>$INSTALL_DIR/cortex-agent</string>
    </array>
    <key>WorkingDirectory</key>
    <string>$INSTALL_DIR</string>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
    <key>StandardErrorPath</key>
    <string>$INSTALL_DIR/agent.err.log</string>
    <key>StandardOutPath</key>
    <string>$INSTALL_DIR/agent.out.log</string>
</dict>
</plist>
EOF
    launchctl unload "$PLIST_PATH" 2>/dev/null || true
    launchctl load "$PLIST_PATH"
    echo "✅ macOS Agent Daemon installed and started!"
    echo "Logs are available at: $INSTALL_DIR/agent.out.log"
else
    echo "Installing Linux systemd service..."
    SERVICE_DIR="$HOME/.config/systemd/user"
    mkdir -p "$SERVICE_DIR"
    SERVICE_PATH="$SERVICE_DIR/cortex-agent.service"
    
    mkdir -p "$INSTALL_DIR/tmp"
    
    cat > "$SERVICE_PATH" << EOF
[Unit]
Description=Cortex Agent Node
After=network.target

[Service]
Environment=TMPDIR=$INSTALL_DIR/tmp
ExecStart=$INSTALL_DIR/cortex-agent
WorkingDirectory=$INSTALL_DIR
Restart=always
RestartSec=5

[Install]
WantedBy=default.target
EOF
    systemctl --user daemon-reload
    systemctl --user enable --now cortex-agent.service
    echo "✅ Linux Agent Daemon installed and started!"
    echo "To view logs: journalctl --user -u cortex-agent -f"
fi

echo ""
echo "🎉 Agent successfully daemonized! You may now close this terminal securely."
