#!/usr/bin/env bash
# Installation script for Monitoring Stack (Prometheus, Grafana, Loki, Alertmanager) in LXC container

set -euo pipefail

source /dev/stdin <<<"$(curl -fsSL https://raw.githubusercontent.com/community-scripts/ProxmoxVE/main/misc/build.func 2>/dev/null || echo '')"

MONITORING_USER="${MONITORING_USER:-monitoring}"
MONITORING_GROUP="${MONITORING_GROUP:-monitoring}"
MONITORING_HOME="/opt/monitoring"

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

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

log_info "Updating system packages..."
export LC_ALL=C
export LANG=C
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get upgrade -y -qq
apt-get install -y -qq \
    docker.io \
    docker-compose \
    curl \
    wget \
    jq \
    ca-certificates \
    gnupg

log_success "System packages updated"

# Start Docker
systemctl enable docker
systemctl start docker

log_info "Creating monitoring user..."
if ! id -u "$MONITORING_USER" &>/dev/null; then
    useradd -r -s /bin/bash -d "$MONITORING_HOME" -m "$MONITORING_USER"
    usermod -aG docker "$MONITORING_USER"
    log_success "Created monitoring user"
else
    log_info "Monitoring user already exists"
    usermod -aG docker "$MONITORING_USER"
fi

# Create directories
log_info "Creating directories..."
mkdir -p "$MONITORING_HOME" \
    "$MONITORING_HOME/prometheus" \
    "$MONITORING_HOME/grafana/provisioning/datasources" \
    "$MONITORING_HOME/grafana/provisioning/dashboards" \
    "$MONITORING_HOME/grafana/dashboards" \
    "$MONITORING_HOME/loki" \
    "$MONITORING_HOME/alertmanager"

chown -R "$MONITORING_USER:$MONITORING_GROUP" "$MONITORING_HOME"

# Create Prometheus config
log_info "Creating Prometheus configuration..."
cat > "$MONITORING_HOME/prometheus/prometheus.yml" <<'EOF'
global:
  scrape_interval: 15s
  evaluation_interval: 15s

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

  - job_name: 'besu-validators'
    static_configs:
      - targets: ['10.3.1.10:9545', '10.3.1.11:9545', '10.3.1.12:9545', '10.3.1.13:9545']

  - job_name: 'besu-sentries'
    static_configs:
      - targets: ['10.3.1.20:9545', '10.3.1.21:9545', '10.3.1.22:9545']

  - job_name: 'besu-rpc'
    static_configs:
      - targets: ['10.3.1.40:9545', '10.3.1.41:9545', '10.3.1.42:9545']

  - job_name: 'oracle-publisher'
    static_configs:
      - targets: ['10.3.1.50:8000']

  - job_name: 'ccip-monitor'
    static_configs:
      - targets: ['10.3.1.51:8000']

  - job_name: 'node-exporter'
    static_configs:
      - targets: ['10.3.1.130:9100']
EOF

# Create Grafana datasource
cat > "$MONITORING_HOME/grafana/provisioning/datasources/datasources.yml" <<'EOF'
apiVersion: 1
datasources:
  - name: Prometheus
    type: prometheus
    access: proxy
    url: http://prometheus:9090
    isDefault: true

  - name: Loki
    type: loki
    access: proxy
    url: http://loki:3100
EOF

# Create docker-compose.yml
log_info "Creating docker-compose configuration..."
cat > "$MONITORING_HOME/docker-compose.yml" <<'EOF'
version: '3.8'

services:
  prometheus:
    image: prom/prometheus:latest
    container_name: prometheus
    volumes:
      - ./prometheus:/etc/prometheus
      - prometheus-data:/prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--storage.tsdb.path=/prometheus'
    ports:
      - "9090:9090"
    restart: unless-stopped
    networks:
      - monitoring-network

  grafana:
    image: grafana/grafana:latest
    container_name: grafana
    volumes:
      - grafana-data:/var/lib/grafana
      - ./grafana/provisioning:/etc/grafana/provisioning
      - ./grafana/dashboards:/var/lib/grafana/dashboards
    environment:
      - GF_SECURITY_ADMIN_USER=admin
      - GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:-admin}
      - GF_USERS_ALLOW_SIGN_UP=false
    ports:
      - "3000:3000"
    depends_on:
      - prometheus
      - loki
    restart: unless-stopped
    networks:
      - monitoring-network

  loki:
    image: grafana/loki:latest
    container_name: loki
    volumes:
      - loki-data:/loki
    command: -config.file=/etc/loki/local-config.yaml
    ports:
      - "3100:3100"
    restart: unless-stopped
    networks:
      - monitoring-network

  promtail:
    image: grafana/promtail:latest
    container_name: promtail
    volumes:
      - /var/log:/var/log:ro
      - ./loki/promtail-config.yml:/etc/promtail/config.yml
    command: -config.file=/etc/promtail/config.yml
    depends_on:
      - loki
    restart: unless-stopped
    networks:
      - monitoring-network

  alertmanager:
    image: prom/alertmanager:latest
    container_name: alertmanager
    volumes:
      - ./alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml
      - alertmanager-data:/alertmanager
    ports:
      - "9093:9093"
    restart: unless-stopped
    networks:
      - monitoring-network

volumes:
  prometheus-data:
  grafana-data:
  loki-data:
  alertmanager-data:

networks:
  monitoring-network:
    driver: bridge
EOF

# Create Alertmanager config
cat > "$MONITORING_HOME/alertmanager/alertmanager.yml" <<'EOF'
global:
  resolve_timeout: 5m

route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 12h
  receiver: 'default-receiver'

receivers:
  - name: 'default-receiver'
    # Configure webhook/email/etc. here
EOF

chown -R "$MONITORING_USER:$MONITORING_GROUP" "$MONITORING_HOME"

# Create systemd service
log_info "Creating systemd service..."
cat > /etc/systemd/system/monitoring-stack.service <<EOF
[Unit]
Description=Monitoring Stack (Prometheus, Grafana, Loki, Alertmanager)
After=docker.service
Requires=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=$MONITORING_HOME
User=$MONITORING_USER
Group=$MONITORING_GROUP
ExecStart=/usr/bin/docker-compose -f $MONITORING_HOME/docker-compose.yml up -d
ExecStop=/usr/bin/docker-compose -f $MONITORING_HOME/docker-compose.yml down
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable monitoring-stack.service

log_success "Monitoring stack installation completed!"
log_info "Services will be available at:"
log_info "  - Prometheus: http://localhost:9090"
log_info "  - Grafana: http://localhost:3000 (admin/admin)"
log_info "  - Loki: http://localhost:3100"
log_info "  - Alertmanager: http://localhost:9093"

