#!/bin/bash
# 宝塔建站完成后钩子：为站点启用 Cloak 路由
# 用法：post_site.sh <域名> <网站根目录>

set -euo pipefail

if [[ -f /etc/cloaka.env ]]; then
    # shellcheck disable=SC1091
    source /etc/cloaka.env
fi
CLOAK_ROOT="${CLOAK_ROOT:-/www/cloaka}"

SITE_DOMAIN="${1:-}"
SITE_PATH="${2:-}"
MARK_BEGIN="# BEGIN IPCLOAKAPI"
MARK_END="# END IPCLOAKAPI"

[[ -z "$SITE_DOMAIN" ]] && exit 0

VHOST="/www/server/panel/vhost/nginx/${SITE_DOMAIN}.conf"
SNIPPET_INST="${CLOAK_ROOT}/deploy/baota/nginx/cloaka-site.conf.installed"

if [[ ! -f "$VHOST" ]]; then
    exit 0
fi

if [[ ! -f "$SNIPPET_INST" ]]; then
    exit 0
fi

if ! grep -qF "$MARK_BEGIN" "$VHOST" 2>/dev/null; then
    {
        echo ""
        echo "$MARK_BEGIN"
        cat "$SNIPPET_INST"
        echo "$MARK_END"
    } >> "$VHOST"
fi

if [[ -f "${CLOAK_ROOT}/cong.php" ]]; then
    php -r "
require '${CLOAK_ROOT}/cong.php';
require '${CLOAK_ROOT}/lib/Cloak/DomainRepository.php';
try {
    \$pdo = DomainRepository::pdo();
    DomainRepository::ensureTable(\$pdo);
    \$host = DomainRepository::normalizeHostname('${SITE_DOMAIN}');
    if (!DomainRepository::findByHostname(\$pdo, \$host)) {
        DomainRepository::add(\$pdo, \$host);
    }
} catch (Throwable \$e) {}
" 2>/dev/null || true
fi

nginx -t 2>/dev/null && nginx -s reload 2>/dev/null || true
