#!/usr/bin/env bash
# =============================================================================
# sanguo_vnpy 阿里云生产环境监控系统部署脚本
# 版本: v1.0
# 作者: 姜维（后勤总督）
# =============================================================================

set -e

echo "========================================================================"
echo "🚀 sanguo_vnpy 监控系统部署"
echo "========================================================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 步骤 1: 安装系统依赖
print_info "步骤 1: 安装系统依赖..."

if command -v apt-get &> /dev/null; then
    sudo apt-get update
    sudo apt-get install -y prometheus node_exporter grafana nginx
elif command -v yum &> /dev/null; then
    sudo yum install -y epel-release
    sudo yum install -y prometheus node_exporter grafana nginx
else
    print_error "不支持的操作系统"
    exit 1
fi

print_success "系统依赖安装完成"

# 步骤 2: 配置 Prometheus
print_info "步骤 2: 配置 Prometheus..."

sudo mkdir -p /etc/prometheus
sudo cat > /etc/prometheus/prometheus.yml << 'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']

  - job_name: 'node_exporter'
    static_configs:
      - targets: ['localhost:9100']

  - job_name: 'sanguo_vnpy'
    static_configs:
      - targets: ['localhost:8080']
    metrics_path: '/metrics'

alerting:
  alertmanagers:
    - static_configs:
        - targets: ['localhost:9093']

rule_files:
  - "/etc/prometheus/alerts.yml"
EOF

# 步骤 3: 配置告警规则
print_info "步骤 3: 配置告警规则..."

sudo cat > /etc/prometheus/alerts.yml << 'EOF'
groups:
  - name: sanguo_vnpy_alerts
    rules:
      - alert: InstanceDown
        expr: up == 0
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "实例 {{ $labels.instance }} 已宕机"
          description: "{{ $labels.job }} 实例 {{ $labels.instance }} 已宕机超过 5 分钟"

      - alert: HighCPUUsage
        expr: 100 - (avg by(instance) (irate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 80
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "实例 {{ $labels.instance }} CPU 使用率过高"
          description: "{{ $labels.instance }} CPU 使用率超过 80%"

      - alert: HighMemoryUsage
        expr: (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100 > 80
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "实例 {{ $labels.instance }} 内存使用率过高"
          description: "{{ $labels.instance }} 内存使用率超过 80%"

      - alert: DiskSpaceLow
        expr: (1 - (node_filesystem_avail_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"})) * 100 > 90
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "实例 {{ $labels.instance }} 磁盘空间不足"
          description: "{{ $labels.instance }} 磁盘使用率超过 90%"

      - alert: VnpyDown
        expr: up{job="sanguo_vnpy"} == 0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "sanguo_vnpy 服务已宕机"
          description: "sanguo_vnpy 服务已宕机超过 2 分钟，请立即检查！"
EOF

# 步骤 4: 配置 Grafana
print_info "步骤 4: 配置 Grafana..."

sudo mkdir -p /etc/grafana/provisioning/datasources
sudo cat > /etc/grafana/provisioning/datasources/prometheus.yml << 'EOF'
apiVersion: 1

datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://localhost:9090
    isDefault: true
    editable: true
EOF

# 步骤 5: 启动服务
print_info "步骤 5: 启动监控服务..."

sudo systemctl enable prometheus
sudo systemctl enable node_exporter
sudo systemctl enable grafana-server

sudo systemctl start prometheus
sudo systemctl start node_exporter
sudo systemctl start grafana-server

# 步骤 6: 配置 Nginx 反向代理
print_info "步骤 6: 配置 Nginx 反向代理..."

sudo cat > /etc/nginx/sites-available/sanguo-monitoring << 'EOF'
server {
    listen 80;
    server_name _;

    location /grafana/ {
        proxy_pass http://localhost:3000/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /prometheus/ {
        proxy_pass http://localhost:9090/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location /node-exporter/ {
        proxy_pass http://localhost:9100/;
        proxy_set_header Host $host;
    }
}
EOF

sudo ln -sf /etc/nginx/sites-available/sanguo-monitoring /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

# 步骤 7: 显示访问信息
print_success "监控系统部署完成！"

echo ""
echo "========================================================================"
echo "📊 监控系统访问信息"
echo "========================================================================"
echo "Grafana:      http://$(hostname -I | awk '{print $1}'):3000"
echo "Prometheus:   http://$(hostname -I | awk '{print $1}'):9090"
echo "Node Exporter: http://$(hostname -I | awk '{print $1}'):9100"
echo ""
echo "默认 Grafana 账号: admin / admin"
echo "========================================================================"
echo ""
