#!/bin/bash

if [[ ! -e "/usr/share/gxde-api" ]] && ! grep -q "Kylin" /etc/os-release; then
    exit 0 # No needed
fi

# 确定目标目录
if grep -q "Kylin" /etc/os-release; then
    TARGET_BASE="/usr/share"
    echo "检测到麒麟系统，使用目标目录: $TARGET_BASE"
else
    TARGET_BASE="/usr/local/share"
    echo "检测到GXDE环境，使用目标目录: $TARGET_BASE"
fi

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
}

# 函数：检查目录并创建符号链接
process_directory() {
    local source_dir="$1"
    local target_dir="$2"
    local name="$3"
    
    if [ -d "$source_dir" ] && [ -n "$(ls -A "$source_dir")" ]; then
        ln -sv $source_dir/* "$target_dir" 2>/dev/null
        find "$target_dir" -xtype l -exec echo '{} is invalid now and going to be cleaned' \; -exec unlink {} \; 2>/dev/null &
    else
        echo "$name directory is empty or does not exist, skipping..."
    fi
}

# 使用动态确定的目标目录
ensure_dir "$TARGET_BASE/applications/"
ensure_dir "$TARGET_BASE/icons/"

# 处理 applications 目录
process_directory "/var/lib/apm/apm/files/ace-env/amber-ce-tools/data-dir/applications/" \
                  "$TARGET_BASE/applications/" "Applications"

# 处理 icons 目录
process_directory "/var/lib/apm/apm/files/ace-env/amber-ce-tools/data-dir/icons/" \
                  "$TARGET_BASE/icons/" "Icons"

# 等待所有后台任务完成
wait