#!/bin/bash

function bash(){
/usr/bin/bash --rcfile <(cat ~/.bashrc; echo "PS1=\"\[\e[37;40m\][\[\e[32;40m\]\u\[\e[37;40m\]@Amber-PM \[\e[36;40m\]\w\[\e[0m\]]\\\$ \"") $@
}
export -f bash
function ensure_dir() {
    local dir="$1"
    
    # 检查目录是否为空
    if [ -z "$dir" ]; then
        echo "错误: 目录路径不能为空"
        return 1
    fi
    
    # 检查目录是否存在
    if [ ! -d "$dir" ]; then
        echo "目录 '$dir' 不存在，正在创建..."
        if mkdir -p "$dir"; then
            echo "成功创建目录 '$dir'"
            return 0
        else
            echo "错误: 无法创建目录 '$dir'"
            return 1
        fi
    else
        return 0
    fi
}
chrootEnvPath="${chrootEnvPath:-$(pwd)/ace-env}"

APM_PKG_NAME="${APM_PKG_NAME:-apm-general}"

non_root_user=$(who  | awk '{print $1}' | head -n 1)
uid=$(id -u $non_root_user)
ensure_dir $HOME/.apm/${APM_PKG_NAME}/

# 根据沙盒模式决定是否创建其他目录
if [ "${APM_USE_SANDBOX:-0}" = "1" ]; then
    ensure_dir $HOME/.apm/${APM_PKG_NAME}/$(basename $(xdg-user-dir DESKTOP))
    ensure_dir $HOME/.apm/${APM_PKG_NAME}/$(basename $(xdg-user-dir DOCUMENTS))
    ensure_dir $HOME/.apm/${APM_PKG_NAME}/$(basename $(xdg-user-dir PICTURES))
    ensure_dir $HOME/.apm/${APM_PKG_NAME}/$(basename $(xdg-user-dir DOWNLOAD))
    ensure_dir $HOME/.apm/${APM_PKG_NAME}/$(basename $(xdg-user-dir VIDEOS))
    ensure_dir $HOME/.apm/${APM_PKG_NAME}/$(basename $(xdg-user-dir MUSIC))
fi

#### This part is for args pharm
if [ "$1" = "" ];then
container_command="bash"
else
container_command="$1"
shift
for arg in "$@"; do
        arg="$(echo "${arg}x" | sed 's|'\''|'\'\\\\\'\''|g')"
        arg="${arg%x}"
        container_command="${container_command} '${arg}'"
done
fi
#########################################################################################
##########合成bwrap 1. 基础函数配置段
# 初始化 EXEC_COMMAND 为 bwrap 基础指令
EXEC_COMMAND="bwrap --dev-bind / / bwrap"

# add_command 函数定义
function add_command() {
    # 参数拼接，考虑到转义和空格的处理
    for arg in "$@"; do
        EXEC_COMMAND="${EXEC_COMMAND} ${arg}"
    done
}

function add_env_var() {
    local var_name="${1}"
    local var_value="${2}"
    if [ "$var_value" != "" ]; then    
	add_command "--setenv $var_name $var_value"
	
    fi
}
##########合成bwrap 2. 特殊需求函数配置段
function cursor_theme_dir_integration() {

local directory=""
if [ "$(id -u)" = "0" ]; then #####We don't want bother root to install themes,but will try to fix the unwriteable issue
	mkdir -p $chrootEnvPath/usr/share/icons
	chmod 777 -R $chrootEnvPath/usr/share/icons
	return
fi

for directory in "/usr/share/icons"/*; do
    # 检查是否为目录
    if [ -d "$directory" ]; then
        # 检查目录中是否存在 cursors 文件
        if [ -d "$directory/cursors" ]; then
        	if [ -w $chrootEnvPath/usr/share/icons ];then
			add_command "--ro-bind-try $directory $directory"
		fi
        fi
    fi
done
}
##########合成bwrap 3. 环境变量和目录绑定配置段
# 添加环境变量和其他初始设置
ENV_VARS=(
    "FAKEROOTDONTTRYCHOWN 1"
    "PULSE_SERVER /run/user/\$uid/pulse/native"
    "PATH /amber-ce-tools/bin-override:\$PATH"
    "IS_ACE_ENV 1"
    "GTK_USE_PORTAL 1"
    "XDG_DATA_DIRS /amber-ce-tools/additional-data-dir-in-container:\$XDG_DATA_DIRS"
)

# 基础绑定目录（始终绑定）
BASE_BIND_DIRS=(
    "--dev-bind $chrootEnvPath/ /"
    "--dev-bind-try /media /media"
    "--dev-bind-try /mnt /mnt"
    "--dev-bind-try /tmp /tmp"
    "--dev-bind-try /data /data"
    "--dev-bind-try /dev /dev"
    "--proc /proc"
    "--dev-bind /sys /sys"
    "--dev-bind /run /run"
    "--dev-bind-try /run/user/\$uid/pulse /run/user/\$uid/pulse"
    "--dev-bind / /host"
    "--ro-bind-try /usr/share/themes /usr/local/share/themes"
    "--ro-bind-try /usr/share/icons /usr/share/icons"
    "--ro-bind-try /usr/share/fonts /usr/local/share/fonts"
    "--dev-bind-try /etc/resolv.conf /etc/resolv.conf"
    "--dev-bind-try /home /home"
    "--dev-bind-try $HOME/.apm/${APM_PKG_NAME}/.deepinwine $HOME/.deepinwine"
)

# 沙盒模式下的额外绑定目录
SANDBOX_BIND_DIRS=(
    "--dev-bind-try $HOME/.apm/${APM_PKG_NAME}/ $HOME/"
    "--dev-bind-try $(xdg-user-dir DESKTOP) $(xdg-user-dir DESKTOP)"
    "--dev-bind-try $(xdg-user-dir DOCUMENTS) $(xdg-user-dir DOCUMENTS)"
    "--dev-bind-try $(xdg-user-dir PICTURES) $(xdg-user-dir PICTURES)"
    "--dev-bind-try $(xdg-user-dir DOWNLOAD) $(xdg-user-dir DOWNLOAD)"
    "--dev-bind-try $(xdg-user-dir VIDEOS) $(xdg-user-dir VIDEOS)"
    "--dev-bind-try $(xdg-user-dir MUSIC) $(xdg-user-dir MUSIC)"
)

# 非沙盒模式下的绑定目录（只绑定.deepinwine）
NON_SANDBOX_BIND_DIRS=(
    "--dev-bind-try $HOME/.deepinwine $HOME/.deepinwine"
)

# 根据 APM_USE_BWRAP 决定是否添加 CAP_SYS_ADMIN
EXTRA_ARGS=()
if [ "${APM_USE_BWRAP:-0}" != "1" ]; then
    EXTRA_ARGS=(
        "--cap-add CAP_SYS_ADMIN"
    )
fi

EXTRA_SCRIPTS=(
#    cursor_theme_dir_integration
)

##########合成bwrap 4. 合成并执行指令
# 逐一添加到 EXEC_COMMAND
for var in "${ENV_VARS[@]}"; do
    add_env_var $var
done

# 添加基础绑定目录
for var in "${BASE_BIND_DIRS[@]}"; do
    add_command "$var"
done

# 根据沙盒模式添加不同的绑定目录
if [ "${APM_USE_SANDBOX:-0}" = "1" ]; then
    for var in "${SANDBOX_BIND_DIRS[@]}"; do
        add_command "$var"
    done
else
    for var in "${NON_SANDBOX_BIND_DIRS[@]}"; do
        add_command "$var"
    done
fi

# 添加额外参数
for var in "${EXTRA_ARGS[@]}"; do
    add_command "$var"
done

for var in "${EXTRA_SCRIPTS[@]}"; do
    $var
done

# 添加最终的 bash 命令
add_command "bash -c \"${container_command}\""

# 输出完整的 EXEC_COMMAND 以查看
# echo "${EXEC_COMMAND}"

# 注意: 实际执行时，请确保所有变量（如 $uid, $chrootEnvPath 等）都已正确定义
eval ${EXEC_COMMAND}