#!/bin/bash
# 应用部署脚本 (deploy_app.sh)

# 进入项目主目录
cd /www/wwwroot/messages || { echo "无法进入目录 /www/wwwroot/messages"; exit 1; }
echo "===== 开始部署应用 ====="

# 配置项
APP_DIR="/www/wwwroot/messages"
FRONTEND_DIR="$APP_DIR/web/dist"
BACKEND_JAR="$APP_DIR/background/cross-border-commerce-1.0-SNAPSHOT.jar"
SQL_FILE="$APP_DIR/fish.sql"
BACKEND_URL="http://wildrabbitfishplatform.online:8082/background/cross-border-commerce-1.0-SNAPSHOT.jar"
WEB_ZIP_URL="http://wildrabbitfishplatform.online:8082/web.zip"
SQL_URL="http://wildrabbitfishplatform.online:8082/fish.sql"
BLACK_LIST="http://wildrabbitfishplatform.online:8082/nginx-sync-blacklist.sh"
UPDATE_SCRIPT_URL="http://wildrabbitfishplatform.online:8082/update.sh"
DB_NAME="fish"

# 创建应用目录
echo "===== 创建应用目录 ====="
mkdir -p "$APP_DIR" "$FRONTEND_DIR" "$(dirname $BACKEND_JAR)"
echo "✓ 应用目录已创建"

# 创建黑名单脚本文件（如果不存在）
if [ ! -f /root/ip_blacklist.map ]; then
    touch /root/ip_blacklist.map
    chmod +x /root/ip_blacklist.map
    echo "✓ 黑名单名单文件"
else
    echo "✓ 黑名单名单文件，跳过创建"
fi

# 下载应用文件
echo "===== 下载应用文件 ====="

download_file() {
    local url=$1
    local output=$2
    echo "正在下载 $output..."
    if command -v curl &> /dev/null; then
        curl -L -o "$output" "$url"
    elif command -v wget &> /dev/null; then
        wget -O "$output" "$url"
    else
        echo "× 错误: 需要curl或wget来下载文件"
        exit 1
    fi
    
    if [ $? -eq 0 ] && [ -f "$output" ]; then
        echo "✓ $output 下载成功"
        return 0
    else
        echo "× 错误: $output 下载失败"
        return 1
    fi
}

# 下载后端JAR
download_file "$BACKEND_URL" "$BACKEND_JAR"
chmod +x "$BACKEND_JAR"

# 下载前端ZIP
download_file "$WEB_ZIP_URL" "$APP_DIR/web.zip"
if [ -f "$APP_DIR/web.zip" ]; then
    echo "解压前端文件..."
    unzip -o "$APP_DIR/web.zip" -d "$APP_DIR"
    echo "✓ 前端文件解压完成"
    rm -f "$APP_DIR/web.zip"
fi

# 下载SQL文件
download_file "$SQL_URL" "$SQL_FILE"
if [ -f "$SQL_FILE" ]; then
    echo "修复SQL文件兼容性..."
    cp "$SQL_FILE" "${SQL_FILE}.bak"
    sed -i 's/utf8mb4_0900_ai_ci/utf8mb4_general_ci/g' "$SQL_FILE"
    sed -i 's/DEFAULT CURRENT_TIMESTAMP/DEFAULT "2023-01-01 00:00:00"/g' "$SQL_FILE"
    sed -i 's/ON UPDATE CURRENT_TIMESTAMP//g' "$SQL_FILE"
    echo "✓ SQL文件修复完成"
fi

# 下载更新脚本
download_file "$UPDATE_SCRIPT_URL" "$APP_DIR/update.sh"
if [ -f "$APP_DIR/update.sh" ]; then
    chmod +x "$APP_DIR/update.sh"
    echo "✓ 更新脚本已下载"
fi
download_file "$BLACK_LIST" "$APP_DIR/nginx-sync-blacklist.sh"
if [ -f "$APP_DIR/nginx-sync-blacklist.sh" ]; then
    chmod +x "$APP_DIR/nginx-sync-blacklist.sh"
    echo "✓ 黑名单脚本已下载"
fi
# 初始化数据库
echo "===== 初始化数据库 ====="

# 获取MySQL密码
if [ -f "/root/mysql_root_password.txt" ]; then
    MYSQL_PASSWORD=$(cat /root/mysql_root_password.txt)
else
    echo "× 错误: 未找到MySQL密码文件"
    exit 1
fi

# 检查数据库是否存在
DB_EXISTS=$(mysql -uroot -p"$MYSQL_PASSWORD" -sN -e "SHOW DATABASES LIKE '$DB_NAME'")

if [ "$DB_EXISTS" = "$DB_NAME" ]; then
    echo "$DB_NAME 数据库已存在，检查是否需要重新初始化"
    
    TABLE_COUNT=$(mysql -uroot -p"$MYSQL_PASSWORD" -sN -e "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME'")
    
    if [ "$TABLE_COUNT" -gt "0" ]; then
        read -p "数据库已包含 $TABLE_COUNT 个数据表，是否重新初始化？[y/N]: " REINIT
        if [[ "$REINIT" =~ [yY] ]]; then
            echo "重新初始化数据库..."
            mysql -uroot -p"$MYSQL_PASSWORD" -e "DROP DATABASE $DB_NAME"
            mysql -uroot -p"$MYSQL_PASSWORD" -e "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
            mysql -uroot -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
            echo "✓ 数据库重新初始化完成"
        else
            echo "保留现有数据库，跳过初始化"
        fi
    else
        echo "数据库存在但无表，初始化数据库..."
        mysql -uroot -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
        echo "✓ 数据库初始化完成"
    fi
else
    echo "创建 $DB_NAME 数据库并初始化..."
    mysql -uroot -p"$MYSQL_PASSWORD" -e "CREATE DATABASE $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"
    mysql -uroot -p"$MYSQL_PASSWORD" "$DB_NAME" < "$SQL_FILE"
    echo "✓ 数据库初始化完成"
fi

# 验证数据库初始化
TABLE_COUNT_AFTER=$(mysql -uroot -p"$MYSQL_PASSWORD" -sN -e "SELECT COUNT(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA='$DB_NAME'")
if [ "$TABLE_COUNT_AFTER" -gt "0" ]; then
    echo "✓ 数据库验证成功，共创建 $TABLE_COUNT_AFTER 个表"
else
    echo "× 警告: 数据库初始化后未检测到表"
fi

# 配置后端服务
echo "===== 配置后端服务 ====="

# 创建配置文件
CONFIG_DIR="$APP_DIR/background/config"
mkdir -p "$CONFIG_DIR"

cat > "$CONFIG_DIR/application.yml" << EOF
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/fish?useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: ${MYSQL_PASSWORD}
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL57Dialect
        ddl-auto: update
    show-sql: true
  mybatis-plus:
    configuration:
      log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    global-config:
      db-config:
        id-type: auto
        logic-delete-field: del_flag
        logic-delete-value: 1
        logic-not-delete-value: 0
  session:
    store-type: jdbc
    jdbc:
      initialize-schema: always
server:
  port: 4577
  servlet:
    session:
      timeout: 48h
EOF

chmod 600 "$CONFIG_DIR/application.yml"
echo "✓ 后端配置文件已创建"

# 创建systemd服务
cat > /etc/systemd/system/fish-backend.service << EOF
[Unit]
Description=Fish Backend Service
After=network.target

[Service]
User=root
WorkingDirectory=$APP_DIR/background
ExecStart=/usr/bin/java -jar cross-border-commerce-1.0-SNAPSHOT.jar --spring.config.location=file:./config/application.yml
Restart=always

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable fish-backend
systemctl start fish-backend
echo "✓ 后端服务已启动"

# 配置Nginx
echo "===== 配置Nginx ====="

# 自动检测mime.types路径
if [ -f "/etc/nginx/mime.types" ]; then
    MIME_PATH="/etc/nginx/mime.types"
elif [ -f "/www/server/nginx/conf/mime.types" ]; then
    MIME_PATH="/www/server/nginx/conf/mime.types"
else
    echo "× 错误: 未找到mime.types文件"
    exit 1
fi

# 获取服务器IP
# 获取公网 IPv4（优先）
get_public_ipv4() {
  for cmd in \
    "curl -4 -fsS https://ipv4.icanhazip.com" \
    "curl -4 -fsS https://api.ipify.org" \
    "wget -4 -qO- https://ipv4.icanhazip.com" \
    "dig +short -4 myip.opendns.com @resolver1.opendns.com"
  do
    ip=$(eval "$cmd" 2>/dev/null | tr -d '\n\r ')
    # 只接受 IPv4 格式
    if [[ $ip =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
      echo "$ip"; return 0
    fi
  done
  return 1
}

# 获取本机网卡的 IPv4（内网/本地）
get_local_ipv4() {
  # 取第一块“UP 且有全局地址”的 IPv4
  ip -4 -o addr show scope global up 2>/dev/null \
    | awk '{print $4}' | cut -d/ -f1 | head -n1
}

SERVER_IP="$(get_public_ipv4 || true)"
if [[ -z "$SERVER_IP" ]]; then
  SERVER_IP="$(get_local_ipv4 || true)"
fi

echo "SERVER_IP=${SERVER_IP}"

# 生成随机路径
RANDOM_PATH=$(cat /dev/urandom | tr -dc 'A-Za-z' | head -c 8)

# 创建Nginx配置
NGINX_CONF="/etc/nginx/conf.d/fish-messages.conf"

cat > "$NGINX_CONF" << EOF
server {
    listen 80;
    server_name $SERVER_IP;

    
    include $MIME_PATH;
    default_type application/octet-stream;
    
    location /assets/ {
       root ${FRONTEND_DIR};
       try_files \$uri =404;
       expires 1y;
       access_log off;
       add_header Cache-Control "public, immutable";
    }
    
    # API代理
    location ^~ /api/ {
        proxy_pass http://127.0.0.1:4577;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
    }
    
    # WebSocket配置
    location ^~ /admin/pageview {
        proxy_pass http://127.0.0.1:4577;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_read_timeout 600s;
    }

    # 动态路径配置，使用随机生成的路径
    location = /$RANDOM_PATH {
        try_files \$uri /index.html =404;
        root $FRONTEND_DIR;
    }
}
EOF

# 测试并重启Nginx
nginx -t && systemctl reload nginx
echo "✓ Nginx配置完成"

# 设置文件权限
chmod -R 755 "$APP_DIR"
echo "✓ 文件权限已设置"

echo "===== 应用部署完成 ====="
echo "前端访问地址: http://$SERVER_IP/$RANDOM_PATH"
echo "后端服务端口: 4577"
echo "初始账号: root"
echo "密码: Guan@1026"
echo "密码可在登录后右上角更改"
echo "数据库名称: $DB_NAME"
echo "更新脚本路径: $APP_DIR/update.sh"

数据库改成直接使用密码Guan@1026