#!/bin/bash
# ============================================================
# kangle + easypanel + PHP + MySQL 从零安装（已在 Ubuntu 22.04 与 CentOS 7 验证）
# 用法: bash deploy/install-stack.sh [--check]
# 关键：以下 4 条缺一条就装不成（都是实测踩出来的）
# ============================================================
set -uo pipefail
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-Kangle@2026}"
KANGLE_VER="${KANGLE_VER:-3.5.21.16}"
FILE_SRC="http://file.kangle.cccyun.cn/file"
PREFIX=/vhs/kangle
REPO="$(cd "$(dirname "$0")/.." && pwd)"

grn(){ printf "\033[32m%s\033[0m\n" "$*"; }
red(){ printf "\033[31m%s\033[0m\n" "$*"; }
step(){ echo; grn "==== $* ===="; }

step "0. 环境探测"
. /etc/os-release 2>/dev/null || true
IS_DEB=$([ -f /etc/debian_version ] && echo 1 || echo 0)
grn "系统: ${PRETTY_NAME:-unknown}  架构: $(uname -m)"
[ "$(id -u)" = "0" ] || { red "需要 root"; exit 1; }
[ "${1:-}" = "--check" ] && { grn "仅检查模式"; exit 0; }

step "1. 依赖"
if [ "$IS_DEB" = "1" ]; then
  apt-get update -qq
  DEBIAN_FRONTEND=noninteractive apt-get install -y wget curl tar gzip sqlite3 mysql-server 2>&1 | tail -2
else
  yum -y install wget curl tar gzip sqlite mysql-server 2>&1 | tail -2
fi

step "2. kangle"
REL=$([ "$IS_DEB" = "1" ] && echo 7 || rpm -q --qf '%{VERSION}' centos-release | cut -d. -f1)
TMP=$(mktemp -d)
wget -q "$FILE_SRC/completed/kangle-ent-$KANGLE_VER-$REL-x64.tar.gz" -O "$TMP/k.tgz" || { red "下载失败"; exit 1; }
mkdir -p "$PREFIX"; tar xzf "$TMP/k.tgz" -C "$PREFIX" --strip-components=1

# 关键 ①：kangle 3311 管理账号（默认 admin/kangle，必须改）
sed -i "s|<admin user='[^']*' password='[^']*'|<admin user='$ADMIN_USER' password='$ADMIN_PASS'|" "$PREFIX/etc/config.xml"
grep -oE "<admin [^/]*/>" "$PREFIX/etc/config.xml" | head -1

step "3. 面板（easypanel 不在 kangle 包里，需单独获取）"
if [ ! -d "$PREFIX/nodewww/webftp" ]; then
  red "未找到面板文件：请从同版本机器复制 /vhs/kangle/nodewww 到本机"
  red "  rsync -a root@源机:/vhs/kangle/nodewww/ $PREFIX/nodewww/"
fi

step "4. PHP 兼容库（Ubuntu 必需，CentOS 可跳过）"
if [ "$IS_DEB" = "1" ] && [ ! -d /opt/compat ]; then
  red "Ubuntu 需补 CentOS 库：libssl.so.10 / libicu*.so.50 / libpng15 等 11 个"
  red "  从 CentOS 机打包后解到 /opt/compat 并 ldconfig"
fi

step "5. 面板凭据（关键 ②：必须与 config.xml 完全一致）"
NCFG="$PREFIX/etc/node.cfg.php"
if [ -f "$NCFG" ]; then
  sed -i "s/'user'=>\"[^\"]*\"/'user'=>\"$ADMIN_USER\"/" "$NCFG"
  sed -i "s/'passwd'=>\"[^\"]*\"/'passwd'=>\"$ADMIN_PASS\"/" "$NCFG"
  grep -oE "'(user|passwd)=>\"[^\"]*\"" "$NCFG" | head -2
else
  red "缺 $NCFG：请从同版本机器复制，否则面板无法登录"
fi

step "6. 启动"
pkill -f "$PREFIX/bin/kangle" 2>/dev/null; sleep 2
"$PREFIX/bin/kangle" >/dev/null 2>&1; sleep 5
ss -lnt 2>/dev/null | grep -E ':(80|3311|3312) ' | head -3

step "7. 验收"
curl -s -o /dev/null -w '登录页: %{http_code}\n' "http://127.0.0.1:3312/admin/?c=session&a=loginForm"
curl -s -o /dev/null -w '登录:   %{http_code} (期望 302)\n' -c /tmp/.ck -b /tmp/.ck \
  --data "username=$ADMIN_USER&passwd=$ADMIN_PASS" \
  "http://127.0.0.1:3312/admin/index.php?c=session&a=login"

step "完成"
cat <<TIP
管理端 http://<IP>:3312/admin/   用户端 http://<IP>:3312/vhost/
账号: $ADMIN_USER / $ADMIN_PASS
下一步: bash deploy/apply-panel-template.sh   # 部署自定义模板
TIP
