#!/bin/bash
set -e

# Triva Remote Agent Installer
# Usage: curl -fsSL https://187.124.171.225/install.sh | bash

SERVER_URL="${TRIVA_SERVER:-ws://187.124.171.225:9002}"
INSTALL_DIR="/opt/triva-remote-agent"
SERVICE_NAME="triva-remote-agent"

echo "=== Triva Remote Agent Installer ==="
echo "Server: $SERVER_URL"
echo ""

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root (use sudo)"
    exit 1
fi

# Detect OS
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
    OS="linux"
elif [[ "$OSTYPE" == "darwin"* ]]; then
    OS="macos"
else
    echo "Unsupported OS: $OSTYPE"
    exit 1
fi

echo "Detected OS: $OS"

# Create directory
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# Download agent
echo "Downloading agent..."
curl -fsSL "https://187.124.171.225/agent.zip" -o agent.zip || {
    echo "Failed to download agent. Using local copy..."
    # Fallback: copy from current directory if available
    cp /tmp/agent.zip . 2>/dev/null || true
}

# Extract
if [ -f agent.zip ]; then
    unzip -o agent.zip
    rm agent.zip
fi

# Make sure Node.js is available
if ! command -v node &> /dev/null; then
    echo "Node.js not found. Installing..."
    if [ "$OS" == "linux" ]; then
        curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
        apt-get install -y nodejs
    elif [ "$OS" == "macos" ]; then
        if command -v brew &> /dev/null; then
            brew install node
        else
            echo "Please install Homebrew first: https://brew.sh"
            exit 1
        fi
    fi
fi

# Create config
 cat > "$INSTALL_DIR/.env" <<EOF
TRIVA_SERVER=$SERVER_URL
TRIVA_NAME=$(hostname)
EOF

# Create systemd service (Linux)
if [ "$OS" == "linux" ]; then
    cat > "/etc/systemd/system/$SERVICE_NAME.service" <<EOF
[Unit]
Description=Triva Remote Agent
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$INSTALL_DIR
Environment=TRIVA_SERVER=$SERVER_URL
Environment=TRIVA_NAME=$(hostname)
ExecStart=/usr/bin/node $INSTALL_DIR/agent.js
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable "$SERVICE_NAME"
    systemctl start "$SERVICE_NAME"
    
    echo "Service installed. Status:"
    systemctl status "$SERVICE_NAME" --no-pager || true
fi

# Create launchd plist (macOS)
if [ "$OS" == "macos" ]; then
    cat > "/Library/LaunchDaemons/com.triva.remote.agent.plist" <<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.triva.remote.agent</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/node</string>
        <string>$INSTALL_DIR/agent.js</string>
    </array>
    <key>EnvironmentVariables</key>
    <dict>
        <key>TRIVA_SERVER</key>
        <string>$SERVER_URL</string>
        <key>TRIVA_NAME</key>
        <string>$(hostname)</string>
    </dict>
    <key>KeepAlive</key>
    <true/>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
EOF

    launchctl load "/Library/LaunchDaemons/com.triva.remote.agent.plist"
    launchctl start com.triva.remote.agent
    
    echo "LaunchDaemon installed."
fi

echo ""
echo "=== Installation Complete ==="
echo "Agent installed at: $INSTALL_DIR"
echo "Configuration: $INSTALL_DIR/.env"
echo ""
echo "To check status:"
if [ "$OS" == "linux" ]; then
    echo "  systemctl status $SERVICE_NAME"
elif [ "$OS" == "macos" ]; then
    echo "  launchctl list | grep triva"
fi
