#!/bin/bash
ACE_dir="/opt/apps/cn.flamescion.bookworm-compatibility-mode/files/bookworm-env"
function linkDir() {
    ensureTargetDir() {
        targetFile=$1
        t=$(dirname "$targetFile")
        mkdir -p "$t"
    }

    source=$1
    target=$2
    sourceDir=$(dirname "$source")
    targetDir=$(dirname "$target")
    find "$source" -type f | while read sourceFile; do
        targetFile="$targetDir/${sourceFile#$sourceDir/}"
        if [ -L "$targetFile" ] && [ "$(readlink "$targetFile")" = "$sourceFile" ]; then
            continue
        else
            rm -f "$targetFile"
        fi

        ensureTargetDir "$targetFile"
        ln -s "$sourceFile" "$targetFile"
    done
}

function do_integrate(){
local file=$1
    if [ -f "$file" ]; then
    	exec_line=$(grep "^Exec=" "$file")
    	# 检查是否是bookworm-run
    	if [[ $exec_line != Exec=bookworm-run* ]]; then
    		echo "$file is detected. Processing host system integration..."
    		sed -i 's|^Exec=\(.*\)|Exec=bookworm-run \1|' "$file"
        	sed -i '/^TryExec=/d' "$file"
        	sed -i '/^Name=/ s/$/ (ACE-Integration)/' "$file"
            	sed -i "/^Name\[${LANGUAGE}\]=/ s/\$/ (ACE-Integration)/" "$file"
            	icon_line=$(grep "^Icon=" "$file")
            	if [[ "$icon_line" == "Icon=/"* ]]; then
    			# 如果Icon=后面接的是/，则添加前缀
    			sed -i 's|^Icon=/|Icon=/opt/apps/cn.flamescion.bookworm-compatibility-mode/files/bookworm-env/|' "$file"
    		fi
		
    	fi
    
    fi
}



for app_dir in $(ls /opt/apps/); do
	for file in /opt/apps/$app_dir/entries/applications/*.desktop;do
	do_integrate $file
	DESKTOP_FILE_NAME=$(basename $file)
	ln -sf "../../../opt/apps/$app_dir/entries/applications/$DESKTOP_FILE_NAME" "/usr/share/applications/"
	linkDir "../../../opt/apps/$app_dir/entries/icons" "/usr/share/icons/"
	
	done
done


for file in /usr/share/applications/*.desktop; do
do_integrate $file
done
find "/usr/share/applications/" -xtype l -delete

