#!/bin/bash
set -euo pipefail

# SafeLine WAF 二进制安装脚本
# 用法: bash install.sh [安装目录]

INSTALL_DIR="${1:-/data/safeline}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

info() { echo -e "${GREEN}[INFO]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; exit 1; }

# 检查 root
if [ "$(id -u)" -ne 0 ]; then
    error "需要 root 权限"
fi

# 检查 Docker
if ! command -v docker &>/dev/null; then
    error "Docker 未安装"
fi

info "安装到: $INSTALL_DIR"

# 创建目录
mkdir -p "$INSTALL_DIR"/{resources/{mgt,postgres/data,nginx,detector,chaos,cache,sock,luigi},logs/{nginx,detector},bin}

# 复制二进制
cp "$SCRIPT_DIR/webserver" "$INSTALL_DIR/bin/"
cp "$SCRIPT_DIR/tcontrollerd" "$INSTALL_DIR/bin/"
chmod +x "$INSTALL_DIR/bin/webserver" "$INSTALL_DIR/bin/tcontrollerd"
info "二进制已复制"

# 生成配置
if [ ! -f "$INSTALL_DIR/.env" ]; then
    POSTGRES_PASSWORD=$(tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 20)
    cat > "$INSTALL_DIR/.env" << EOF
SAFELINE_DIR=$INSTALL_DIR
POSTGRES_PASSWORD=$POSTGRES_PASSWORD
MGT_PORT=9443
RELEASE=
CHANNEL=
REGION=
IMAGE_PREFIX=chaitin
IMAGE_TAG=9.3.9
SUBNET_PREFIX=192.168.90
ARCH_SUFFIX=
EOF
    info ".env 已生成"
fi

# 复制 compose
if [ -f "$SCRIPT_DIR/compose.yaml" ]; then
    cp "$SCRIPT_DIR/compose.yaml" "$INSTALL_DIR/docker-compose.yaml"
    info "compose.yaml 已复制"
fi

# 启动
cd "$INSTALL_DIR"
if docker compose version &>/dev/null; then
    docker compose up -d --remove-orphans
else
    docker-compose up -d --remove-orphans
fi

info "启动完成!"
info "管理面板: https://$(hostname -I | awk '{print $1}'):9443/"
info "获取密码: docker exec safeline-mgt /app/mgt-cli reset-admin --once"
