#!/bin/bash

# LogVista Agent Installation Script for Linux
set -e

echo "============================================"
echo "LogVista Agent Installation Script"
echo "============================================"

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo "Error: Node.js is not installed. Please install Node.js 16 or higher."
    echo "Visit: https://nodejs.org/en/download/"
    exit 1
fi

# Check Node.js version
NODE_VERSION=$(node -v | cut -d'v' -f2)
REQUIRED_VERSION="16.0.0"

if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$NODE_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]; then
    echo "Error: Node.js version $NODE_VERSION is not supported. Please install version 16.0.0 or higher."
    exit 1
fi

echo "✓ Node.js $NODE_VERSION detected"

# Get installation directory
read -p "Enter installation directory [/opt/logvista-agent]: " INSTALL_DIR
INSTALL_DIR=${INSTALL_DIR:-/opt/logvista-agent}

# Check if directory already exists
if [ -d "$INSTALL_DIR" ]; then
    read -p "Directory $INSTALL_DIR already exists. Overwrite? [y/N]: " OVERWRITE
    if [[ ! $OVERWRITE =~ ^[Yy]$ ]]; then
        echo "Installation cancelled."
        exit 1
    fi
    rm -rf "$INSTALL_DIR"
fi

# Create installation directory
sudo mkdir -p "$INSTALL_DIR"
sudo chown $(whoami):$(whoami) "$INSTALL_DIR"

echo "Installing LogVista Agent to $INSTALL_DIR..."

# Copy files
cp -r . "$INSTALL_DIR/"

# Navigate to installation directory
cd "$INSTALL_DIR"

# Install dependencies
echo "Installing dependencies..."
npm install --production

# Create logs directory
mkdir -p logs/offline

# Make the main script executable
chmod +x src/index.js

# Create systemd service file
sudo tee /etc/systemd/system/logvista-agent.service > /dev/null <<EOF
[Unit]
Description=LogVista Agent - System monitoring and log collection
After=network.target

[Service]
Type=simple
User=$(whoami)
WorkingDirectory=$INSTALL_DIR
ExecStart=/usr/bin/node src/index.js
Restart=always
RestartSec=10
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd
sudo systemctl daemon-reload

echo "============================================"
echo "LogVista Agent installed successfully!"
echo "============================================"
echo ""
echo "Next steps:"
echo "1. Edit the configuration file: $INSTALL_DIR/config/agent.config.json"
echo "2. Update the central_system.url and central_system.token"
echo "3. Configure your projects in the projects array"
echo "4. Start the service: sudo systemctl start logvista-agent"
echo "5. Enable auto-start: sudo systemctl enable logvista-agent"
echo ""
echo "Useful commands:"
echo "  Status: sudo systemctl status logvista-agent"
echo "  Logs:   sudo journalctl -u logvista-agent -f"
echo "  Stop:   sudo systemctl stop logvista-agent"
echo ""
echo "Configuration file location: $INSTALL_DIR/config/agent.config.json"
echo "Installation directory: $INSTALL_DIR"
