#!/bin/bash
# IPCLOAKAPI 宝塔一键安装脚本
# 用法：sudo bash install_bt.sh [--upgrade] [--source /path/to/cloaka]
set -euo pipefail

UPGRADE=0
SOURCE_DIR=""
CLOAK_ROOT="/www/cloaka"
ADMIN_DOMAIN=""
PHP_VER="82"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --upgrade) UPGRADE=1; shift ;;
        --source) SOURCE_DIR="${2:-}"; shift 2 ;;
        --root) CLOAK_ROOT="${2:-}"; shift 2 ;;
        *) echo "未知参数: $1"; exit 1 ;;
    esac
done

if [[ "$(id -u)" -ne 0 ]]; then
    echo "请使用 root 运行：sudo bash install_bt.sh"
    exit 1
fi

if [[ ! -d /www/server/panel ]]; then
    echo "未检测到宝塔面板目录 /www/server/panel"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -z "$SOURCE_DIR" ]]; then
    SOURCE_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
fi

detect_php() {
    for v in 82 83 81 80 74; do
        if [[ -f "/www/server/php/${v}/etc/php.ini" ]]; then
            PHP_VER="$v"
            return
        fi
    done
    PHP_VER="82"
}

detect_php
PHP_INCLUDE="/www/server/nginx/conf/enable-php-${PHP_VER}.conf"
if [[ ! -f "$PHP_INCLUDE" ]]; then
    PHP_INCLUDE="enable-php.conf"
fi

echo "=== IPCLOAKAPI 宝塔安装 ==="
echo "源码目录: $SOURCE_DIR"
echo "安装目录: $CLOAK_ROOT"
echo "PHP 版本: ${PHP_VER}"

if [[ "$UPGRADE" -eq 0 ]]; then
    read -r -p "管理后台域名（如 cloak-admin.example.com，可留空稍后手动建站）: " ADMIN_DOMAIN
fi

mkdir -p "$CLOAK_ROOT"
if command -v rsync >/dev/null 2>&1; then
    rsync -a --delete \
        --exclude '.git' --exclude 'node_modules' --exclude '.cursor' \
        --exclude 'cong.php' --exclude '.install.lock' --exclude 'check_config/*_config.php' \
        "$SOURCE_DIR/" "$CLOAK_ROOT/"
else
    cp -a "$SOURCE_DIR/." "$CLOAK_ROOT/"
fi

chown -R www:www "$CLOAK_ROOT"
chmod -R u=rwX,g=rX,o=rX "$CLOAK_ROOT"
chmod -R u=rwX,g=rwX,o= "$CLOAK_ROOT/check_config" 2>/dev/null || mkdir -p "$CLOAK_ROOT/check_config" && chown www:www "$CLOAK_ROOT/check_config"
touch "$CLOAK_ROOT/jump.txt" "$CLOAK_ROOT/nt.txt" "$CLOAK_ROOT/err.txt" 2>/dev/null || true
chown www:www "$CLOAK_ROOT"/*.txt 2>/dev/null || true

# 注册建站钩子
HOOK_DIR="/www/server/panel/hook"
mkdir -p "$HOOK_DIR"
install -m 755 "$SCRIPT_DIR/hook/post_site.sh" "$HOOK_DIR/cloaka_post_site.sh"
install -m 755 "$SCRIPT_DIR/hook/post_site_del.sh" "$HOOK_DIR/cloaka_post_site_del.sh"

# 环境变量供钩子使用
ENV_FILE="/etc/cloaka.env"
echo "CLOAK_ROOT=${CLOAK_ROOT}" > "$ENV_FILE"
chmod 644 "$ENV_FILE"

# 预处理 Nginx 片段
SNIPPET_INST="${CLOAK_ROOT}/deploy/baota/nginx/cloaka-site.conf.installed"
sed -e "s|__CLOAK_ROOT__|${CLOAK_ROOT}|g" -e "s|__PHP_INCLUDE__|${PHP_INCLUDE}|g" \
    "$SCRIPT_DIR/nginx/cloaka-site.conf" > "$SNIPPET_INST"

if [[ -n "$ADMIN_DOMAIN" && "$UPGRADE" -eq 0 ]]; then
  if command -v bt >/dev/null 2>&1; then
    echo "正在创建管理站点: $ADMIN_DOMAIN"
    bt site add "$ADMIN_DOMAIN" "$CLOAK_ROOT" 2>/dev/null || true
  fi
  ADMIN_VHOST="/www/server/panel/vhost/nginx/${ADMIN_DOMAIN}.conf"
  if [[ -f "$ADMIN_VHOST" ]] && ! grep -q 'cloaka-admin' "$ADMIN_VHOST" 2>/dev/null; then
    cat "$SCRIPT_DIR/nginx/cloaka-admin.conf" >> "$ADMIN_VHOST"
  fi
fi

# 确保域名表（已安装 cong 时）
if [[ -f "$CLOAK_ROOT/cong.php" ]]; then
    php -r "
require '${CLOAK_ROOT}/cong.php';
require '${CLOAK_ROOT}/lib/Cloak/DomainRepository.php';
\$pdo = DomainRepository::pdo();
DomainRepository::ensureTable(\$pdo);
echo 'cloak_site_domains OK\n';
" 2>/dev/null || true
fi

nginx -t && nginx -s reload || true

echo ""
echo "============================================"
echo "安装文件已就绪。"
if [[ ! -f "$CLOAK_ROOT/.install.lock" ]]; then
    if [[ -n "$ADMIN_DOMAIN" ]]; then
        echo "请浏览器访问: https://${ADMIN_DOMAIN}/install.php"
    else
        echo "请在宝塔新建站点，根目录指向: ${CLOAK_ROOT}"
        echo "然后访问: https://你的管理域名/install.php"
    fi
else
    echo "已检测到安装锁，进入后台: ${ADMIN_DOMAIN:-你的管理域名}/dashboard.php"
fi
echo "新建业务站点后，请在后台「站点域名」添加域名并关联配置。"
echo "============================================"
