#!/bin/bash
# 无 node 时的轻量混淆：整文件 base64 + TextDecoder/new Function 包裹。
# 强度远低于 confuse.js（javascript-obfuscator），仅作兼容兜底。
# 参数：webAppName configBase [pkgRoot]

ERROR_ICON="❌"
INFO_ICON="ℹ️"
CHECK_ICON="✅"

webAppName="${1:-${WEB_APP_NAME}}"
configBase="${2:-${CONFIG_FILE_NAME:-sysconfig}}"
pkgRoot="${3:-}"

if [ -z "$pkgRoot" ]; then
  pkgRoot="$(cd "$(dirname "$0")/../.." && pwd)"
fi

if [ -z "$webAppName" ]; then
  echo -e "${ERROR_ICON} 缺少前端应用目录名：请传入第 1 个参数或设置 WEB_APP_NAME" >&2
  exit 1
fi

filepath="${pkgRoot}/${webAppName}/${configBase}.js"
echo -e "${INFO_ICON} 文件路径:${filepath}"

if [ ! -f "$filepath" ]; then
  echo -e "${ERROR_ICON} 文件不存在: ${filepath}" >&2
  exit 1
fi

# 已混淆过则跳过，避免重复包裹
if grep -q '__WINNER_BASH_OBFUSCATED__' "$filepath" 2>/dev/null; then
  echo -e "${CHECK_ICON} 配置文件已混淆，跳过"
  exit 0
fi

# 可移植：避免 GNU 专用的 base64 -w 0
b64=$(base64 < "$filepath" | tr -d '\n\r')
if [ -z "$b64" ]; then
  echo -e "${ERROR_ICON} base64 编码失败" >&2
  exit 1
fi

tmpfile="${filepath}.obf.$$"
# UTF-8 安全：atob → Uint8Array → TextDecoder，再 new Function 执行
cat > "$tmpfile" <<EOF
/* __WINNER_BASH_OBFUSCATED__ */
(new Function(new TextDecoder("utf-8").decode(Uint8Array.from(atob("${b64}"),function(c){return c.charCodeAt(0)}))))();
EOF

if [ $? -ne 0 ]; then
  rm -f "$tmpfile"
  echo -e "${ERROR_ICON} 写入临时文件失败" >&2
  exit 1
fi

mv "$tmpfile" "$filepath"
echo -e "${CHECK_ICON} bash 轻量混淆完成"
echo -e "${INFO_ICON} 更新路径:${filepath}"
exit 0
