#!/bin/bash
set -e

# ============================================================
#  OpsMind 一键安装脚本
#  使用方法: bash <(curl -sSL https://releases.wymsn.com/install.sh)
# ============================================================

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()    { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()    { echo -e "${YELLOW}[WARN]${NC} $1"; }
error()   { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

VERSION="${OPSMIND_VERSION:-v2.0.0}"
BASE_URL="https://releases.wymsn.com/releases/${VERSION}"
INSTALL_DIR="/opt/opsmind"
CONFIG_DIR="/etc/opsmind"
PANEL_PORT="${OPSMIND_PORT:-27300}"
PANEL_USER="${OPSMIND_USER:-admin}"
PANEL_PASS="${OPSMIND_PASS:-opsmind@$(date +%Y)}"

# ── 检查 root ──────────────────────────────────────────────
[ "$(id -u)" -eq 0 ] || error "请使用 root 用户运行此脚本"

# ── 检测系统 ───────────────────────────────────────────────
OS=""
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$ID
fi
[[ "$OS" =~ ^(ubuntu|debian|centos|rhel|rocky|almalinux)$ ]] || error "不支持的操作系统: $OS"

# ── 检测架构 ───────────────────────────────────────────────
ARCH=$(uname -m)
case $ARCH in
    x86_64)  ARCH="amd64" ;;
    aarch64) ARCH="arm64" ;;
    *)       error "不支持的架构: $ARCH" ;;
esac

info "============================================"
info "  OpsMind 安装程序 ${VERSION}"
info "  系统: $OS | 架构: $ARCH"
info "  端口: $PANEL_PORT"
info "============================================"

# ── 安装依赖 ───────────────────────────────────────────────
info "安装基础依赖..."
if [[ "$OS" =~ ^(ubuntu|debian)$ ]]; then
    apt-get update -q
    apt-get install -y -q curl wget docker.io docker-compose || true
    systemctl enable docker --now 2>/dev/null || true
else
    yum install -y curl wget docker docker-compose || true
    systemctl enable docker --now 2>/dev/null || true
fi

# ── 创建目录结构 ───────────────────────────────────────────
info "创建目录结构..."
mkdir -p "$INSTALL_DIR"/{opsmind,apps,backup,docker}
mkdir -p "$INSTALL_DIR"/opsmind/{db,log,resource,resource/apps,resource/icon}
mkdir -p "$CONFIG_DIR"

# ── 下载二进制 ─────────────────────────────────────────────
info "下载 opsmind-agent..."
curl -sSL "$BASE_URL/linux/$ARCH/opsmind-agent" -o "$INSTALL_DIR/opsmind-agent"
info "下载 opsmind-core..."
curl -sSL "$BASE_URL/linux/$ARCH/opsmind-core" -o "$INSTALL_DIR/opsmind-core"
chmod +x "$INSTALL_DIR/opsmind-agent" "$INSTALL_DIR/opsmind-core"

# ── 写配置文件 ─────────────────────────────────────────────
info "生成配置文件..."
cat > "$CONFIG_DIR/opsmind.yaml" << EOF
base:
  install_dir: /opt
  mode: dev
  is_demo: false
  is_intl: false
  is_offline: false
  port: ${PANEL_PORT}
  username: ${PANEL_USER}
  password: ${PANEL_PASS}
  version: ${VERSION}

remote_url:
  app_repo: https://apps.wymsn.com
  repo_url: https://releases.wymsn.com/package/v2
  resource_url: https://releases.wymsn.com/resource/v2

log:
  level: info
  time_zone: Asia/Shanghai
  log_name: OpsMind-Core
  log_suffix: .log
  max_backup: 10
EOF

cat > "$CONFIG_DIR/agent.yaml" << EOF
base:
  install_dir: /opt
  mode: dev
  is_demo: false
  is_offline: false

remote_url:
  app_repo: https://apps.wymsn.com
  repo_url: https://releases.wymsn.com/package/v2
  resource_url: https://releases.wymsn.com/resource/v2

log:
  level: info
  time_zone: Asia/Shanghai
  log_name: OpsMind
  log_suffix: .log
  max_backup: 10
EOF

# ── 写 systemd 服务 ────────────────────────────────────────
info "注册系统服务..."
cat > /etc/systemd/system/opsmind-agent.service << EOF
[Unit]
Description=OpsMind Agent Service
After=network.target docker.service
Wants=docker.service

[Service]
Type=simple
ExecStart=/opt/opsmind/opsmind-agent --config /etc/opsmind/agent.yaml
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/opsmind-core.service << EOF
[Unit]
Description=OpsMind Core Service
After=network.target opsmind-agent.service
Requires=opsmind-agent.service

[Service]
Type=simple
ExecStart=/opt/opsmind/opsmind-core --config /etc/opsmind/opsmind.yaml
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# ── 创建 Docker 网络 ──────────────────────────────────────────
info "创建 1panel-network Docker 网络..."
docker network create 1panel-network 2>/dev/null || true

# ── 启动服务 ───────────────────────────────────────────────
info "启动服务..."
systemctl daemon-reload
systemctl enable opsmind-agent opsmind-core
systemctl start opsmind-agent
sleep 2
systemctl start opsmind-core
sleep 3

# ── 检查状态 ───────────────────────────────────────────────
if systemctl is-active --quiet opsmind-agent && systemctl is-active --quiet opsmind-core; then
    SERVER_IP=$(curl -sSf --max-time 3 https://api.ipify.org 2>/dev/null || hostname -I | awk '{print $1}')
    echo ""
    echo -e "${GREEN}============================================${NC}"
    echo -e "${GREEN}  OpsMind 安装成功！${NC}"
    echo -e "${GREEN}============================================${NC}"
    echo -e "  访问地址: ${YELLOW}http://${SERVER_IP}:${PANEL_PORT}${NC}"
    echo -e "  用户名:   ${YELLOW}${PANEL_USER}${NC}"
    echo -e "  密码:     ${YELLOW}${PANEL_PASS}${NC}"
    echo -e "${GREEN}============================================${NC}"
    echo ""
else
    error "服务启动失败，请检查日志: journalctl -u opsmind-agent -n 30"
fi
