#!/bin/bash
# Smart deploy script for NOFX on CentOS 7
# - Step-aware: detects if each step already succeeded and skips
# - Options: --skip-go, --skip-talib, --skip-nginx, --non-interactive
# Usage examples:
#   bash scripts/centos7-deploy-smart.sh --non-interactive
#   bash scripts/centos7-deploy-smart.sh --skip-go --non-interactive

set -euo pipefail

TA_LIB_VERSION="0.4.0"
GO_VERSION="1.25.0"
APP_DIR="$(pwd)"
INSTALL_PREFIX="/usr/local"
APP_INSTALL_DIR="/opt/nofx"
WEB_DIST_TARGET="/opt/nofx/web-dist"
STATE_DIR="/var/lib/nofx-deploy"

info() { echo -e "\033[1;32m[INFO]\033[0m $*"; }
warn() { echo -e "\033[1;33m[WARN]\033[0m $*"; }
err()  { echo -e "\033[1;31m[ERR]\033[0m  $*"; }

[[ $EUID -ne 0 ]] && { err "请以 root 身份运行此脚本 (sudo -i)。"; exit 1; }
mkdir -p "$STATE_DIR"

# ===== Options =====
SKIP_GO=false
SKIP_TALIB=false
SKIP_NGINX=false
NON_INTERACTIVE=false

for arg in "$@"; do
  case "$arg" in
    --skip-go) SKIP_GO=true ;;
    --skip-talib) SKIP_TALIB=true ;;
    --skip-nginx) SKIP_NGINX=true ;;
    --non-interactive) NON_INTERACTIVE=true ;;
    -h|--help)
      cat <<EOF
Usage: $0 [--skip-go] [--skip-talib] [--skip-nginx] [--non-interactive]
- 默认会智能检测：如果某一步已完成则跳过
- --skip-go      强制跳过 Go 安装
- --skip-talib   强制跳过 TA-Lib 安装
- --skip-nginx   强制跳过 Nginx 安装与前端配置
- --non-interactive  非交互模式，自动选择跳过已完成步骤
EOF
      exit 0 ;;
    *) echo "Unknown option: $arg"; exit 1 ;;
  esac
done

has_go() { command -v go >/dev/null 2>&1; }
has_talib() { ldconfig -p 2>/dev/null | grep -qi 'ta_lib'; }
has_nginx() { command -v nginx >/dev/null 2>&1; }
service_active() { systemctl is-active --quiet "$1"; }
unit_exists() { [[ -f "/etc/systemd/system/$1.service" ]]; }

# 确保在脚本运行期间 Go 环境变量始终有效
load_go_env() {
  if [[ -f /etc/profile.d/go.sh ]]; then
    # 加载持久化环境变量
    source /etc/profile.d/go.sh || true
  fi
  # 如果go未在PATH但已安装，手动补PATH
  if [[ -x /usr/local/go/bin/go ]]; then
    export PATH="/usr/local/go/bin:$PATH"
  fi
  # 避免隐式下载更高版本toolchain
  export GOTOOLCHAIN="${GOTOOLCHAIN:-local}"
  # 使用更稳定的代理链（国内/全球均可fallback）
  export GOPROXY="${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct}"
  # 校验和数据库保持默认；如网络受限可改为 off
  export GOSUMDB="${GOSUMDB:-sum.golang.org}"
}

# Interactive confirmations
if [ "$NON_INTERACTIVE" = false ]; then
  if has_go && [ "$SKIP_GO" = false ]; then
    read -r -p "检测到已安装 Go ($(go version))，是否跳过安装? [Y/n] " ans || true
    case "${ans,,}" in n*) SKIP_GO=false ;; *) SKIP_GO=true ;; esac
  fi
  if has_talib && [ "$SKIP_TALIB" = false ]; then
    read -r -p "检测到 TA-Lib 已存在，是否跳过编译安装? [Y/n] " ans2 || true
    case "${ans2,,}" in n*) SKIP_TALIB=false ;; *) SKIP_TALIB=true ;; esac
  fi
  if has_nginx && [ "$SKIP_NGINX" = false ]; then
    read -r -p "检测到 Nginx 已存在，是否跳过安装与配置? [Y/n] " ans3 || true
    case "${ans3,,}" in n*) SKIP_NGINX=false ;; *) SKIP_NGINX=true ;; esac
  fi
fi



# ===== Go install (auto-skip) =====
if [ "$SKIP_GO" = true ] || has_go; then
  info "跳过 Go 安装。当前：$(has_go && go version || echo '未检测到')"
else
  info "安装 Go ${GO_VERSION}..."
  GO_TGZ="go${GO_VERSION}.linux-amd64.tar.gz"
  cd /tmp && rm -rf /usr/local/go || true
  if wget -q "https://go.dev/dl/${GO_TGZ}"; then
    tar -C /usr/local -xzf "${GO_TGZ}"
  else
    warn "下载 Go ${GO_VERSION} 失败，尝试回退到 1.20.12"
    GO_TGZ="go1.20.12.linux-amd64.tar.gz"
    wget -q "https://go.dev/dl/${GO_TGZ}"
    tar -C /usr/local -xzf "${GO_TGZ}"
  fi
  cat >/etc/profile.d/go.sh <<'EOF'
export PATH=/usr/local/go/bin:$PATH
export GOTOOLCHAIN=local
export GOPROXY=https://goproxy.cn,https://proxy.golang.org,direct
export GOSUMDB=sum.golang.org
EOF
  load_go_env
fi
load_go_env
info "Go 版本: $(has_go && go version || echo '未安装')"

# ===== TA-Lib (auto-skip) =====
if [ "$SKIP_TALIB" = true ] || has_talib; then
  info "跳过 TA-Lib 安装。"
else
  info "尝试通过 yum 安装 TA-Lib（若不可用则源码编译）..."
  if yum -y install ta-lib ta-lib-devel; then
    info "已通过 yum 安装 TA-Lib。"
  else
    warn "yum 仓库未提供 TA-Lib，改为源码编译安装。"
    info "编译安装 TA-Lib ${TA_LIB_VERSION}（单线程，避免并行编译问题）..."
    cd /tmp
    wget -q "http://prdownloads.sourceforge.net/ta-lib/ta-lib-${TA_LIB_VERSION}-src.tar.gz" -O ta-lib-${TA_LIB_VERSION}-src.tar.gz || \
      wget -q "https://mirrors.ustc.edu.cn/sourceforge/ta-lib/ta-lib-${TA_LIB_VERSION}-src.tar.gz" -O ta-lib-${TA_LIB_VERSION}-src.tar.gz || \
      wget -q "https://mirrors.tuna.tsinghua.edu.cn/sourceforge/ta-lib/ta-lib-${TA_LIB_VERSION}-src.tar.gz" -O ta-lib-${TA_LIB_VERSION}-src.tar.gz
    rm -rf ta-lib-src && mkdir -p ta-lib-src
    tar -xzf ta-lib-${TA_LIB_VERSION}-src.tar.gz -C ta-lib-src --strip-components=1
    cd ta-lib-src
    ./configure --prefix="${INSTALL_PREFIX}"
    make -j1 || { warn "首次 make 失败，执行 make clean 后重试"; make clean && make -j1; }
    make install
    echo "/usr/local/lib" > /etc/ld.so.conf.d/ta-lib.conf
    ldconfig
  fi
fi

# ===== Backend build (skip if service active and binary exists) =====
cd "${APP_DIR}"
load_go_env
export CGO_ENABLED=1
export GOTOOLCHAIN="local"
export GOPROXY="https://goproxy.cn,https://proxy.golang.org,direct"

NEED_BUILD=true
if [[ -x "${APP_INSTALL_DIR}/nofx" ]] && service_active nofx; then
  NEED_BUILD=false
fi

if [ "$NEED_BUILD" = true ]; then
  info "构建后端..."
  go mod download
  mkdir -p "${APP_INSTALL_DIR}"
  if [[ -f "${APP_DIR}/config.json" ]]; then
    cp -f "${APP_DIR}/config.json" "${APP_INSTALL_DIR}/config.json"
  elif [[ -f "${APP_DIR}/config.json.example" ]]; then
    cp -f "${APP_DIR}/config.json.example" "${APP_INSTALL_DIR}/config.json"
  fi
  go build -trimpath -ldflags="-s -w" -o "${APP_INSTALL_DIR}/nofx" .
else
  info "检测到后端已构建且服务运行，跳过构建。"
fi

# ===== Systemd service (skip if exists and active) =====
if unit_exists nofx && service_active nofx; then
  info "systemd 服务已存在且运行，跳过配置。"
else
  info "配置 systemd 服务..."
  cat >/etc/systemd/system/nofx.service <<EOF
[Unit]
Description=NOFX Backend Service
After=network.target

[Service]
Type=simple
WorkingDirectory=${APP_INSTALL_DIR}
ExecStart=${APP_INSTALL_DIR}/nofx
Restart=always
RestartSec=5
Environment=LD_LIBRARY_PATH=/usr/local/lib

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable --now nofx || true
  sleep 2
fi
systemctl status nofx --no-pager || true

# ===== Nginx (auto-skip) =====
if [ "$SKIP_NGINX" = true ]; then
  info "跳过 Nginx 安装与前端配置。"
elif has_nginx && [[ -f /etc/nginx/conf.d/nofx.conf ]]; then
  info "检测到 Nginx 已安装且已配置，跳过。"
else
  info "安装并配置 Nginx..."
  yum -y install nginx || true
  mkdir -p "${WEB_DIST_TARGET}"
  if [[ -d "${APP_DIR}/web/dist" ]]; then
    rsync -a --delete "${APP_DIR}/web/dist/" "${WEB_DIST_TARGET}/" || cp -r "${APP_DIR}/web/dist" "${WEB_DIST_TARGET}" || true
  else
    warn "未检测到 web/dist。请在开发机上 npm ci && npm run build，并将 dist 上传至 ${WEB_DIST_TARGET}。"
  fi
  cat >/etc/nginx/conf.d/nofx.conf <<'EOF'
server {
    listen 80 default_server;
    server_name _;
    root /opt/nofx/web-dist;
    index index.html;

    location /api/ {
        proxy_pass http://127.0.0.1:8099/api/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /health {
        return 200 "ok";
        add_header Content-Type text/plain;
    }
}
EOF
  systemctl enable --now nginx || true
fi

# ===== Health checks =====
set +e
curl -fsS http://127.0.0.1:8080/api/health && echo "[OK] Backend health passed" || echo "[WARN] Backend health not responding yet"
curl -fsS http://127.0.0.1/health && echo "[OK] Nginx health passed" || echo "[WARN] Nginx health not responding yet"
set -e

info "完成。前端访问: http://<服务器IP>/"
info "多次运行安全；已完成的步骤会自动跳过。支持 --skip-go/--skip-talib/--skip-nginx/--non-interactive。"