84 lines
2.1 KiB
Bash
Executable File
84 lines
2.1 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
server_bind_read_env_value() {
|
|
local file="$1"
|
|
local key="$2"
|
|
awk -F= -v key="$key" '$1 == key { sub(/^[^=]*=/, ""); print; exit }' "$file" | tr -d '\r'
|
|
}
|
|
|
|
server_bind_write_env_value() {
|
|
local file="$1"
|
|
local key="$2"
|
|
local value="$3"
|
|
local tmp_file
|
|
tmp_file="$(mktemp "${file}.XXXXXX")"
|
|
awk -v key="$key" -v value="$value" '
|
|
BEGIN { replaced = 0 }
|
|
$0 ~ "^" key "=" {
|
|
if (!replaced) {
|
|
print key "=" value
|
|
replaced = 1
|
|
}
|
|
next
|
|
}
|
|
{ print }
|
|
END {
|
|
if (!replaced) print key "=" value
|
|
}
|
|
' "$file" > "$tmp_file"
|
|
chmod --reference="$file" "$tmp_file" 2>/dev/null || true
|
|
mv "$tmp_file" "$file"
|
|
}
|
|
|
|
infer_server_http_bind_ip() {
|
|
local file="$1"
|
|
local public_api_url
|
|
public_api_url="$(server_bind_read_env_value "$file" "NUXT_PUBLIC_BASE_APIURL")"
|
|
|
|
case "$public_api_url" in
|
|
/api|/api/*|http://127.0.0.1:*|https://127.0.0.1:*|http://localhost:*|https://localhost:*)
|
|
printf '%s\n' "127.0.0.1"
|
|
;;
|
|
http://*|https://*)
|
|
printf '%s\n' "0.0.0.0"
|
|
;;
|
|
*)
|
|
printf '%s\n' "127.0.0.1"
|
|
;;
|
|
esac
|
|
}
|
|
|
|
init_server_http_bind_ip() {
|
|
local file="${1:-.env}"
|
|
local override="${2:-}"
|
|
local current target
|
|
|
|
if [ ! -f "$file" ]; then
|
|
echo "❌ 未找到环境文件: $file" >&2
|
|
return 1
|
|
fi
|
|
|
|
current="$(server_bind_read_env_value "$file" "SERVER_HTTP_BIND_IP")"
|
|
target="${override:-$current}"
|
|
if [ -z "$target" ]; then
|
|
target="$(infer_server_http_bind_ip "$file")"
|
|
fi
|
|
|
|
case "$target" in
|
|
127.0.0.1|0.0.0.0) ;;
|
|
*)
|
|
echo "❌ SERVER_HTTP_BIND_IP 仅支持 127.0.0.1 或 0.0.0.0,当前为: $target" >&2
|
|
return 1
|
|
;;
|
|
esac
|
|
|
|
if [ "$current" != "$target" ]; then
|
|
server_bind_write_env_value "$file" "SERVER_HTTP_BIND_IP" "$target"
|
|
echo " ✓ SERVER_HTTP_BIND_IP=$target"
|
|
fi
|
|
}
|
|
|
|
if [ "${BASH_SOURCE[0]}" = "$0" ]; then
|
|
init_server_http_bind_ip "${1:-.env}" "${2:-}"
|
|
fi
|