#!/usr/bin/env bash
set -euo pipefail

# 剧核工厂一键部署入口。
# 第一次执行会询问部署参数并保存到 API/deploy/.deploy.conf；以后执行会自动复用。
# 完整部署流程在同目录的 deploy_with_ssl.sh 中，便于后续单独重复执行。

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
API_ROOT="$(realpath "$SCRIPT_DIR/..")"
PROJECT_ROOT="$(realpath "$API_ROOT/..")"
CONFIG_FILE="$SCRIPT_DIR/.deploy.conf"

if [ -s "$CONFIG_FILE" ]; then
    # shellcheck disable=SC1090
    source "$CONFIG_FILE"
else
    SAVED_DOMAIN_INPUT=""
    SAVED_USER_EMAIL=""
    EXISTING_NGINX_CONFIG="/etc/nginx/conf.d/juyou_ai.conf"
    if [ -f "$EXISTING_NGINX_CONFIG" ]; then
        SAVED_DOMAIN_INPUT="$(sed -n -E 's/^[[:space:]]*server_name[[:space:]]+([^;]+);.*$/\1/p' "$EXISTING_NGINX_CONFIG" | head -n 1)"
        SAVED_DOMAIN_INPUT="${SAVED_DOMAIN_INPUT//_/}"
        SAVED_DOMAIN_INPUT="$(printf '%s' "$SAVED_DOMAIN_INPUT" | xargs)"
    fi
    if [ -z "$SAVED_DOMAIN_INPUT" ]; then
        read -r -p "域名（多个域名空格分隔，将全部追加到证书；不申请 SSL 填 _）[_]: " SAVED_DOMAIN_INPUT
        SAVED_DOMAIN_INPUT="${SAVED_DOMAIN_INPUT:-_}"
    fi
    FIRST_SAVED_DOMAIN="${SAVED_DOMAIN_INPUT%% *}"
    EXISTING_CERT_READY=false
    if [ -n "$FIRST_SAVED_DOMAIN" ] && [ -f "/etc/nginx/ssl/${FIRST_SAVED_DOMAIN}_bundle.crt" ] && [ -f "/etc/nginx/ssl/${FIRST_SAVED_DOMAIN}.key" ]; then
        EXISTING_CERT_READY=true
    fi
    if [ "$SAVED_DOMAIN_INPUT" != "_" ] && [ "$EXISTING_CERT_READY" = true ]; then
        echo "检测到当前域名的现有证书，复用域名和证书：$SAVED_DOMAIN_INPUT"
    elif [ "$SAVED_DOMAIN_INPUT" != "_" ]; then
        read -r -p "SSL 证书邮箱（申请新证书；不申请 SSL 直接回车）: " SAVED_USER_EMAIL
    fi
    cat >"$CONFIG_FILE" <<EOF
# 部署脚本自动保存的配置，可直接编辑后重新运行。
SAVED_DOMAIN_INPUT=$(printf '%q' "$SAVED_DOMAIN_INPUT")
SAVED_USER_EMAIL=$(printf '%q' "$SAVED_USER_EMAIL")
EOF
fi

SAVED_DOMAIN_INPUT="${SAVED_DOMAIN_INPUT//$'\r'/}"
SAVED_USER_EMAIL="${SAVED_USER_EMAIL//$'\r'/}"
export SAVED_DOMAIN_INPUT SAVED_USER_EMAIL
if [ -z "${JCF_ENV_SOURCE:-}" ] && [ -f /tmp/juyou_ai.env ]; then
    export JCF_ENV_SOURCE=/tmp/juyou_ai.env
fi
exec bash "$SCRIPT_DIR/deploy_with_ssl.sh" "$API_ROOT"
