#!/data/data/com.termux/files/usr/bin/bash

BASHRC_FILE="$HOME/.bashrc"
CONFIG_MARKER="# --- Termux Environment Fix Block (Managed by Script) ---"
FIX_PREFIX="/data/data/com.termux/files/usr"
FIX_HOME="/data/data/com.termux/files/home"

echo "开始对Termux环境进行全面检查和修复..."
echo "Starting comprehensive check and fix for the Termux environment..."

if grep -qF "$CONFIG_MARKER" "$BASHRC_FILE" 2>/dev/null; then
    echo "检测到修复配置已存在于 $BASHRC_FILE 中。"
    echo "Detected that the fix configuration already exists in $BASHRC_FILE."
    echo "无需重复操作。脚本将退出。"
    echo "No repeated action is needed. The script will exit."
    echo "如果需要强制重新写入，请先手动删除文件中的旧配置块。"
    echo "If you need to force a rewrite, please manually remove the old configuration block from the file first."
    exit 0
fi

if [ -s "$BASHRC_FILE" ]; then
    BACKUP_NAME=".bashrc.bak_$(date +%Y%m%d-%H%M%S)"
    echo "发现已存在的 .bashrc 文件，正在备份到 ~/$BACKUP_NAME ..."
    echo "Found an existing .bashrc file, backing it up to ~/$BACKUP_NAME ..."
    cp "$BASHRC_FILE" "$HOME/$BACKUP_NAME"
fi

echo "正在将一套标准的环境配置写入 $BASHRC_FILE ..."
echo "Writing a standard environment configuration set to $BASHRC_FILE ..."
cat << EOF >> "$BASHRC_FILE"

$CONFIG_MARKER
export TERMUX__PREFIX="$FIX_PREFIX"
export HOME="$FIX_HOME"
case ":\$PATH:" in
    *":\$TERMUX__PREFIX/bin:"*)
        ;;
    *)
        export PATH="\$TERMUX__PREFIX/bin:\$TERMUX__PREFIX/bin/applets:\$PATH"
        ;;
esac
case ":\$LD_LIBRARY_PATH:" in
    *":\$TERMUX__PREFIX/lib:"*)
        ;;
    *)
        export LD_LIBRARY_PATH="\$TERMUX__PREFIX/lib:\$LD_LIBRARY_PATH"
        ;;
esac
export LD_PRELOAD="\$TERMUX__PREFIX/lib/libtermux-exec.so"
export TMPDIR="\$TERMUX__PREFIX/tmp"
export LANG="\${LANG:-en_US.UTF-8}"
export TERM="\${TERM:-xterm-256color}"
export EDITOR="\${EDITOR:-nano}"
export VISUAL="\${VISUAL:-nano}"
# --- End of Termux Environment Fix Block ---
EOF

echo "配置写入成功。正在为当前脚本会话加载新配置..."
echo "Configuration written successfully. Loading new configuration for the current script session..."
source "$BASHRC_FILE"

echo ""
echo "--------------------------------------------------"
echo "以下是部分关键环境变量在当前脚本会话中的值："
echo "The values of key environment variables in the current script session are as follows:"
echo ""
echo "  HOME: $HOME"
echo "  TERMUX__PREFIX: $TERMUX__PREFIX"
echo "  LANG: $LANG"
echo "  PATH: $PATH"
echo ""
echo "--------------------------------------------------"

echo "已尝试设置终端环境"
echo "Attempted to set up the terminal environment."

echo -e "\n\033[43;31m请强制停止ZeroTermux后重新打开\033[0m"
echo -e "\033[43;31mForce stop ZeroTermux and reopen it\033[0m"