#!/bin/bash
# =============================================================================
# Zabbix Agent 2 Installation Script for NORDABIZ-01
# =============================================================================
# Usage: sudo ./zabbix_agent_install.sh
# Server: NORDABIZ-01 (10.22.68.249)
# Zabbix Server: zabbix4norda (10.22.68.126)
# =============================================================================

set -e

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

# Configuration
ZABBIX_SERVER="10.22.68.126"
HOSTNAME="NORDABIZ-01"
ZABBIX_VERSION="7.0"

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   log_error "This script must be run as root (use sudo)"
   exit 1
fi

echo ""
echo "=============================================="
echo "Zabbix Agent 2 Installation for NORDABIZ-01"
echo "=============================================="
echo ""

# Step 1: Check if already installed
log_info "Checking existing installation..."
if systemctl is-active --quiet zabbix-agent2 2>/dev/null; then
    log_warn "Zabbix Agent 2 is already installed and running"
    read -p "Do you want to reconfigure? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 0
    fi
fi

# Step 2: Detect OS
log_info "Detecting OS..."
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
    VERSION=$VERSION_ID
    log_info "Detected: $PRETTY_NAME"
else
    log_error "Cannot detect OS"
    exit 1
fi

# Step 3: Install Zabbix repository
log_info "Adding Zabbix repository..."
case $OS in
    ubuntu)
        wget -q https://repo.zabbix.com/zabbix/${ZABBIX_VERSION}/ubuntu/pool/main/z/zabbix-release/zabbix-release_${ZABBIX_VERSION}-2+ubuntu${VERSION}_all.deb -O /tmp/zabbix-release.deb
        dpkg -i /tmp/zabbix-release.deb
        rm /tmp/zabbix-release.deb
        apt update
        ;;
    debian)
        wget -q https://repo.zabbix.com/zabbix/${ZABBIX_VERSION}/debian/pool/main/z/zabbix-release/zabbix-release_${ZABBIX_VERSION}-2+debian${VERSION}_all.deb -O /tmp/zabbix-release.deb
        dpkg -i /tmp/zabbix-release.deb
        rm /tmp/zabbix-release.deb
        apt update
        ;;
    *)
        log_error "Unsupported OS: $OS"
        exit 1
        ;;
esac

# Step 4: Install Zabbix Agent 2
log_info "Installing Zabbix Agent 2..."
apt install -y zabbix-agent2 zabbix-agent2-plugin-postgresql

# Step 5: Backup original config
log_info "Backing up original configuration..."
cp /etc/zabbix/zabbix_agent2.conf /etc/zabbix/zabbix_agent2.conf.orig

# Step 6: Configure Zabbix Agent 2
log_info "Configuring Zabbix Agent 2..."
cat > /etc/zabbix/zabbix_agent2.conf << EOF
# Zabbix Agent 2 Configuration
# Generated by zabbix_agent_install.sh
# Server: ${HOSTNAME}

# === CONNECTION SETTINGS ===
Server=${ZABBIX_SERVER}
ServerActive=${ZABBIX_SERVER}
Hostname=${HOSTNAME}
ListenPort=10050

# === LOGGING ===
LogFile=/var/log/zabbix/zabbix_agent2.log
LogFileSize=10
DebugLevel=3

# === SECURITY ===
EnableRemoteCommands=0
DenyKey=system.run[*]

# === PERFORMANCE ===
Timeout=30
BufferSend=5
BufferSize=100

# === INCLUDES ===
Include=/etc/zabbix/zabbix_agent2.d/*.conf
EOF

# Step 7: Create NordaBiznes custom monitoring config
log_info "Creating NordaBiznes monitoring configuration..."
cat > /etc/zabbix/zabbix_agent2.d/nordabiznes.conf << 'EOF'
# ============================================
# NordaBiznes Hub - Custom Zabbix Monitoring
# Server: NORDABIZ-01 (10.22.68.249)
# ============================================

# --- FLASK APPLICATION ---
UserParameter=nordabiznes.health,curl -s -o /dev/null -w "%{http_code}" http://localhost:5000/health 2>/dev/null | grep -q "200" && echo 1 || echo 0
UserParameter=nordabiznes.response_time,curl -s -o /dev/null -w "%{time_total}" http://localhost:5000/health 2>/dev/null | awk '{printf "%.0f", $1*1000}'
UserParameter=nordabiznes.workers,pgrep -f "gunicorn.*nordabiznes" | wc -l
UserParameter=nordabiznes.service_status,systemctl is-active nordabiznes >/dev/null 2>&1 && echo 1 || echo 0
UserParameter=nordabiznes.memory_mb,ps aux | grep -E "gunicorn.*nordabiznes|python.*app.py" | grep -v grep | awk '{sum+=$6} END {printf "%.0f", sum/1024}'

# --- POSTGRESQL DATABASE ---
UserParameter=postgresql.status,pg_isready -h localhost -p 5432 >/dev/null 2>&1 && echo 1 || echo 0
UserParameter=postgresql.connections,sudo -u postgres psql -t -c "SELECT count(*) FROM pg_stat_activity WHERE datname='nordabiznes'" 2>/dev/null | tr -d ' '
UserParameter=postgresql.db_size_mb,sudo -u postgres psql -t -c "SELECT pg_database_size('nordabiznes')/1024/1024" 2>/dev/null | tr -d ' '
UserParameter=postgresql.longest_query_sec,sudo -u postgres psql -t -c "SELECT COALESCE(EXTRACT(EPOCH FROM (now() - query_start))::int, 0) FROM pg_stat_activity WHERE datname='nordabiznes' AND state='active' ORDER BY query_start LIMIT 1" 2>/dev/null | tr -d ' ' || echo 0

# --- DISK USAGE ---
UserParameter=nordabiznes.disk_usage_mb,du -sm /var/www/nordabiznes 2>/dev/null | cut -f1
UserParameter=nordabiznes.disk_percent,df /var/www/nordabiznes 2>/dev/null | tail -1 | awk '{print $5}' | tr -d '%'
UserParameter=nordabiznes.file_count,find /var/www/nordabiznes -type f 2>/dev/null | wc -l
UserParameter=nordabiznes.logs_size_mb,du -sm /var/log/nordabiznes* 2>/dev/null | awk '{sum+=$1} END {print sum}' || echo 0

# --- SYSTEM RESOURCES ---
UserParameter=system.load1,cat /proc/loadavg | cut -d' ' -f1
UserParameter=system.memory_percent,free | grep Mem | awk '{printf "%.1f", $3/$2 * 100}'
UserParameter=system.swap_percent,free | grep Swap | awk '{if($2>0) printf "%.1f", $3/$2 * 100; else print 0}'
UserParameter=system.uptime_sec,cat /proc/uptime | cut -d' ' -f1 | cut -d'.' -f1

# --- AI CHAT METRICS ---
UserParameter=nordabiznes.chat_messages_today,sudo -u postgres psql -t -d nordabiznes -c "SELECT COUNT(*) FROM ai_chat_messages WHERE created_at >= CURRENT_DATE" 2>/dev/null | tr -d ' ' || echo 0
UserParameter=nordabiznes.active_conversations,sudo -u postgres psql -t -d nordabiznes -c "SELECT COUNT(DISTINCT conversation_id) FROM ai_chat_messages WHERE created_at >= NOW() - INTERVAL '24 hours'" 2>/dev/null | tr -d ' ' || echo 0
EOF

# Set permissions
chown root:zabbix /etc/zabbix/zabbix_agent2.d/nordabiznes.conf
chmod 640 /etc/zabbix/zabbix_agent2.d/nordabiznes.conf

# Step 8: Configure sudoers for zabbix
log_info "Configuring sudoers for Zabbix..."
cat > /etc/sudoers.d/zabbix << 'EOF'
# Zabbix agent permissions for NordaBiznes monitoring
# SECURITY: Only specific commands allowed without password

zabbix ALL=(postgres) NOPASSWD: /usr/bin/psql -t -c *
zabbix ALL=(postgres) NOPASSWD: /usr/bin/psql -t -d nordabiznes -c *
EOF

chmod 440 /etc/sudoers.d/zabbix

# Step 9: Configure firewall if UFW is active
if command -v ufw &> /dev/null && ufw status | grep -q "Status: active"; then
    log_info "Configuring UFW firewall..."
    ufw allow from ${ZABBIX_SERVER} to any port 10050 proto tcp comment "Zabbix Server"
fi

# Step 10: Start and enable service
log_info "Starting Zabbix Agent 2..."
systemctl daemon-reload
systemctl restart zabbix-agent2
systemctl enable zabbix-agent2

# Step 11: Verify installation
echo ""
log_info "Verifying installation..."
echo ""

echo "Service status:"
systemctl status zabbix-agent2 --no-pager -l | head -15

echo ""
echo "Testing UserParameters:"
echo "----------------------"
echo -n "agent.ping: "
zabbix_agent2 -t agent.ping 2>/dev/null || echo "FAILED"
echo -n "nordabiznes.health: "
zabbix_agent2 -t nordabiznes.health 2>/dev/null || echo "FAILED"
echo -n "nordabiznes.service_status: "
zabbix_agent2 -t nordabiznes.service_status 2>/dev/null || echo "FAILED"
echo -n "postgresql.status: "
zabbix_agent2 -t postgresql.status 2>/dev/null || echo "FAILED"

echo ""
echo "=============================================="
log_info "Installation complete!"
echo "=============================================="
echo ""
echo "Next steps:"
echo "1. Add host in Zabbix UI: http://${ZABBIX_SERVER}/zabbix"
echo "   - Host name: ${HOSTNAME}"
echo "   - Interface: Agent 10.22.68.249:10050"
echo "   - Templates: Linux by Zabbix agent, PostgreSQL by Zabbix agent 2"
echo ""
echo "2. Test connection from Zabbix server:"
echo "   zabbix_get -s 10.22.68.249 -k agent.ping"
echo ""
