#!/bin/bash
# ===========================================================================
# 茗管家 ZenTea ERP 客户端一键自动化安装与部署脚本
# 适用宿主机系统：Ubuntu 20/22/24, CentOS 7/8/9
# ===========================================================================

set -e

# 云端授权中心 API 与一键分发站配置（可根据实际部署域名进行替换）
LICENSE_SERVER_URL="https://api.jinghuatea.com"
DEPLOY_SERVER_URL="https://deploy.jinghuatea.com"

echo "==========================================================================="
# 统一使用“茗管家”，不使用“茗掌柜”
echo "       欢迎使用 茗管家 ZenTea ERP 一键自动化安装程序"
echo "==========================================================================="

# ==========================================
# 1. 参数解析与校验
# ==========================================
LICENSE_KEY=""

# 解析命令行参数
while [ "$#" -gt 0 ]; do
    case "$1" in
        --license-key=*)
            LICENSE_KEY="${1#*=}"
            shift
            ;;
        *)
            echo "[ERROR] 未知参数: $1"
            echo "用法: bash install.sh --license-key=\"CLIENT_LICENSE_KEY\""
            exit 1
            ;;
    esac
done

if [ -z "$LICENSE_KEY" ]; then
    echo "[ERROR] 必须指定 --license-key 参数！"
    echo "用法: bash install.sh --license-key=\"CLIENT_LICENSE_KEY\""
    exit 1
fi

echo "[INFO] 正在向授权中心校验授权密钥: $LICENSE_KEY ..."

# 2. 联网向云端校验 License 合法性，并获取基本信息
LICENSE_INFO_URL="${LICENSE_SERVER_URL}/api/v1/releases/latest?product_code=zentea&current_version=0.0.0&license_key=${LICENSE_KEY}"
HTTP_RESP=$(curl -s -w "%{http_code}" "$LICENSE_INFO_URL" -o /tmp/license_resp.json || true)

if [ "$HTTP_RESP" != "200" ]; then
    echo "[ERROR] 授权密钥校验失败 (HTTP STATUS: $HTTP_RESP)！请确保网络畅通且 License Key 有效。"
    rm -f /tmp/license_resp.json
    exit 1
fi

# 检查云端是否返回了合法更新版本（使用 Python 3 进行防呆解析，完全兼容单/多介质）
LATEST_VERSION=$(python3 -c "import json; data=json.load(open('/tmp/license_resp.json')); print(data.get('latest_version', ''))" 2>/dev/null || true)
IMAGE_PATH=$(python3 -c "import json; data=json.load(open('/tmp/license_resp.json')); print(data.get('artifact', {}).get('artifact_path', ''))" 2>/dev/null || true)
IMAGE_DIGEST=$(python3 -c "import json; data=json.load(open('/tmp/license_resp.json')); print(data.get('artifact', {}).get('artifact_digest', ''))" 2>/dev/null || true)

if [ -z "$LATEST_VERSION" ] || [ -z "$IMAGE_PATH" ]; then
    echo "[ERROR] 授权中心未能返回合法的基础发布版本介质，请联系系统供应商确认版本状态。"
    rm -f /tmp/license_resp.json
    exit 1
fi

echo "[OK] 授权校验成功！"
echo "  - 授权激活版本: $LATEST_VERSION"
echo "  - 基础镜像路径: $IMAGE_PATH"

rm -f /tmp/license_resp.json

# ==========================================
# 3. 宿主机基础依赖与 Docker 环境自动检测/安装
# ==========================================
echo "[INFO] 正在检测并安装系统基础依赖及 Docker 环境..."

# 检测系统类型
if [ -f /etc/redhat-release ]; then
    OS="centos"
elif [ -f /etc/lsb-release ] || [ -f /etc/debian_version ]; then
    OS="ubuntu"
else
    echo "[ERROR] 本脚本暂不支持该操作系统类型，请手动安装 Docker / Python 3 后运行。"
    exit 1
fi

# 安装 Docker 与 Curl / Python 3
if ! command -v docker &> /dev/null; then
    echo "[INFO] 正在安装 Docker 引擎..."
    if [ "$OS" == "centos" ]; then
        yum install -y yum-utils
        yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
        yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    else
        apt-get update
        apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release python3
        mkdir -p /etc/apt/keyrings
        curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
        echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
        apt-get update
        apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin
    fi
    systemctl enable docker
    systemctl start docker
fi

# 安装 python 依赖 (cryptography 与 PyYAML)
echo "[INFO] 正在安装守护进程 Python3 基础依赖..."
if [ "$OS" == "centos" ]; then
    yum install -y python3-pip python3-cryptography python3-yaml || true
else
    apt-get update
    apt-get install -y python3-pip python3-cryptography python3-yaml || true
fi

# 创建运行目录与系统用户组
sudo groupadd zentea 2>/dev/null || true
sudo mkdir -p /etc/zentea-upgrader /opt/zentea-upgrader /var/lib/zentea-upgrader/backups /run/zentea-upgrader
sudo chmod 770 /run/zentea-upgrader
sudo chown -R root:zentea /run/zentea-upgrader

# ==========================================
# 4. 下载升级守护进程代码与公钥证书
# ==========================================
echo "[INFO] 正在下载系统安全证书与守护进程程序..."

# 从云端一键分发服务器拉取签名验证公钥 (宿主机验签唯一可信源)
curl -fsSL "${DEPLOY_SERVER_URL}/static/keys/public.pem" -o /etc/zentea-upgrader/official_public_key.pem

# 从云端一键分发服务器拉取 upgrader 守护进程代码
curl -fsSL "${DEPLOY_SERVER_URL}/static/scripts/upgrader.py" -o /opt/zentea-upgrader/upgrader.py

# ==========================================
# 5. 生成强数据库密码凭证与本地配置文件
# ==========================================
echo "[INFO] 正在生成本地高安全数据库隔离凭证与升级配置..."

DB_PASSWORD=$(date +%s | sha256sum | base64 | head -c 32)

# 写入 db.env 并限定 0600 特权权限
cat > /etc/zentea-upgrader/db.env << EOF
POSTGRES_USER=postgres
POSTGRES_PASSWORD=${DB_PASSWORD}
POSTGRES_DB=zentea_db
EOF
chmod 0600 /etc/zentea-upgrader/db.env

# 写入 config.yaml 升级配置文件
cat > /etc/zentea-upgrader/config.yaml << EOF
compose_file: "/opt/zentea/docker-compose.yml"
compose_project: "zentea"
backend_service: "backend"
backend_image_env_key: "BACKEND_IMAGE"
frontend_service: "frontend"
frontend_image_env_key: "FRONTEND_IMAGE"
health_check_url: "http://localhost:8000/api/v1/health"
docker_network: "zentea-network"
db_container: "zentea-db"
backup_dir: "/var/lib/zentea-upgrader/backups"
compose_env_file: "/opt/zentea/.env"
EOF

# ==========================================
# 6. 注册并拉起 Systemd 升级守护进程服务
# ==========================================
echo "[INFO] 正在注册并运行系统后台升级守护进程 (zentea-upgrader)..."

cat > /etc/systemd/system/zentea-upgrader.service << EOF
[Unit]
Description=ZenTea ERP Safe Online Upgrader Daemon
After=network.target docker.service
Requires=docker.service

[Service]
Type=simple
User=root
WorkingDirectory=/opt/zentea-upgrader
ExecStart=/usr/bin/python3 /opt/zentea-upgrader/upgrader.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now zentea-upgrader.service

# ==========================================
# 7. 首次一键拉起 ERP 容器系统
# ==========================================
echo "[INFO] 正在拉取最新的 茗管家 ERP 系统镜像并首次部署运行..."

sudo mkdir -p /opt/zentea
ZENTEA_GID=$(getent group zentea | cut -d: -f3 || echo "1001")

# 生成容器端 .env 文件
cat > /opt/zentea/.env << EOF
POSTGRES_USER=postgres
POSTGRES_PASSWORD=${DB_PASSWORD}
POSTGRES_DB=zentea_db
REDIS_PASSWORD=$(date +%s | sha256sum | base64 | head -c 20)
SECRET_KEY=$(date +%s | sha256sum | base64 | head -c 48)
ENV=production
VERSION=${LATEST_VERSION}
ENABLE_ONLINE_UPGRADE=true
ZENTEA_GID=${ZENTEA_GID}
BACKEND_IMAGE=${IMAGE_PATH}@${IMAGE_DIGEST}
EOF

# 从云端一键分发服务器拉取最新的 docker-compose 模版
curl -fsSL "${DEPLOY_SERVER_URL}/static/templates/docker-compose.client.yml" -o /opt/zentea/docker-compose.yml

# 执行首次拉起
cd /opt/zentea
docker compose pull
docker compose up -d

echo "==========================================================================="
echo "       🎉 恭喜！茗管家 ZenTea ERP 进销存系统已顺利部署并启动完成！"
echo "==========================================================================="
echo "系统当前版本: $LATEST_VERSION"
echo "访问端口: http://localhost:8000"
echo "默认管理员账号: admin"
echo "首次登录后请务必在 [系统设置] 菜单中修改您的默认管理员密码！"
echo "==========================================================================="
