#!/usr/bin/env bash
# 仅供江西206的11服务器手工执行；不创建备份，不改变权重。
# AI/所列文件模块普通查询也固定11；不处理后台写文件或历史文件迁移。
set -eu
cd /usr/local/nginx/conf/vhost
jx_file=jx206-entry.conf
jx_nginx=/usr/local/nginx/sbin/nginx

# 只适配此前回读的“一个默认location”入口，拒绝重复或覆盖后续修改。
test "$(grep -cE '^[[:space:]]*location[[:space:]]' "$jx_file")" -eq 1
grep -qE '^[[:space:]]*location / *\{' "$jx_file"
grep -q 'proxy_pass http://jx206_application;' "$jx_file"
if grep -q 'JX206_FILE_LOCAL_' "$jx_file"; then
    echo '已存在文件规则，停止，未修改。' >&2
    exit 1
fi
"$jx_nginx" -t

sed -i '/^[[:space:]]*location \/ *{/i\
    # JX206_FILE_LOCAL_BEGIN\
    location ~* ^/(static/(upload|download)/|uploads/|downloads/|aizhct/) { proxy_pass http://127.0.0.1:8080; }\
    location ~* ^/(p|m|api)/.*(upload|download|export|qrcode|annex|filedelete|dishesrecognizeimgdelete|hardware_?log|sign_?daka|modifyuser) { proxy_pass http://127.0.0.1:8080; }\
    location ~* ^/(p|m|api)/(common|activity|article|restaurant|staff|nutrition|nutrition_?station|supplier|train_?experience|work_?flow|dining_?config)/ { proxy_pass http://127.0.0.1:8080; }\
    location = /index.php { proxy_pass http://127.0.0.1:8080; }\
    location = / { proxy_pass http://127.0.0.1:8080; }\
    # JX206_FILE_LOCAL_END
' "$jx_file"

if ! "$jx_nginx" -t; then
    sed -i '/# JX206_FILE_LOCAL_BEGIN/,/# JX206_FILE_LOCAL_END/d' "$jx_file"
    echo '检查失败，已移除本次新增块，未重载。' >&2
    exit 1
fi
"$jx_nginx" -s reload
echo '已发送重载信号；需检查入口日志确认规则实际生效，不能仅凭此行验收。'
