#!/bin/bash

# $1 sessionbus.list
## com.kylin.processStateManage.service
## com.kylin.processStateManage.service
# $2 systembus.list
## com.kylin.processStateManage.service
## com.kylin.processStateManage.service
# $3 namespace: .docker or .$UUID
# $4 outputpath: Indicate where to place the modified .service file

SYSTEM_BUS_SERVICE_PATH="/usr/share/dbus-1/system-services/"
SESSION_BUS_SERVICE_PATH="/usr/share/dbus-1/services/"
OUTPUTPATH="/opt/compatibility_layer/config/bus/confliction/"
SYSTEMSERVICEDEST="sysbuslist/"
SESSIONSERVICEDEST="sesbuslist/"
SYSTEMCONFDEST="sysconflist/"
EXECPREFIX="/usr/bin/kare run "

#arg1 is path where arg2 .service file placed, for system _ /usr/share/dbus-1/system-services/, for session _ /usr/share/dbus-1/services/
#arg2 is .service filename like org.ukui.SSS.service
#arg3 is namespace to add like .docker 
#arg4 is output path, where org.ukui.SSS.docker.service placed
function namespace_conflicted_services() {
    infilepath="$1"
    servicefilename="$2"
    infile=$infilepath$servicefilename
    namespace="$3"
    outpath="$4"
    container="$5 "

    extension=".service"
    servicename=$(echo "$servicefilename" | awk -F "$extension" '{print $1}')
    echo "Service name is $servicename"
    # outfile=$outpath$(basename "$2")$namespace$extension
    outfile=$outpath$servicename$namespace$extension

    echo "[dbus-add-namespace]Input arg is $infilepath , $infile, $namespace, output is $outfile ..."

    #如果bak文件不存在，则创建
    if [ -f "$outfile" ]; then
        echo "file $outfile already exist"
        truncate --size=0 -c $outfile
    else
        touch "$outfile"
        echo "file $outfile created"
    fi
    
    # 逐行读取输入文件内容，并在每行的内容中插入 ".docker" 字符串    
    # cat $infile | while read line; do
    #     echo $line
    # done
    while IFS= read -r line;
    do
        if echo "$line" | grep -q "Name="; then
            modified_line=$line$namespace
            echo "$modified_line" >> "$outfile"
            continue
        elif echo "$line" | grep -q "Exec="; then
            idstr="Exec="
            insertpos=$(expr index "$line" "$idstr" + ${#idstr})            
            modified_line="${line:0:insertpos-1}${EXECPREFIX}${container}${line:insertpos-1}"
            echo "$modified_line" >> "$outfile"
            continue
        fi
        echo "$line" >> "$outfile"
    done < "$infile"

    if [ $infilepath == $SYSTEM_BUS_SERVICE_PATH ]; then
        echo "$servicename=$servicename$namespace" >> "/opt/compatibility_layer/config/bus/confliction/dbus-sys-proxy.list"
    elif [ $infilepath == $SESSION_BUS_SERVICE_PATH ]; then
        echo "$servicename=$servicename$namespace" >> "/opt/compatibility_layer/config/bus/confliction/dbus-sess-proxy.list"
    fi
}

function namespace_conflicted_confs() {
    infilepath="$1"
    conffilename="$2"
    infile=$infilepath$conffilename
    namespace="$3"
    outpath="$4"

    extension=".conf"
    confname=$(echo "$conffilename" | awk -F "$extension" '{print $1}')
    echo "Conf name is $confname"
    outfile=$outpath$confname$namespace$extension

    echo "[dbus-add-namespace-conf]Input arg is $infilepath , $infile, $namespace, output is $outfile ..."

    #如果bak文件不存在，则创建
    if [ -f "$outfile" ]; then
        echo "file $outfile already exist"
        truncate --size=0 -c $outfile
    else
        touch "$outfile"
        echo "file $outfile created"
    fi
    
    keyword1="send_destination="
    keyword2="own="
    regexConfName="(^|[^[:alnum:]_])$confname([^[:alnum:]_]|$)"
    regexKey1="(^|[^[:alnum:]_])$keyword1"
    regexKey2="(^|[^[:alnum:]_])$keyword2"

    # 逐行读取输入文件内容，并在每行的内容中插入 ".docker" 字符串
    while IFS= read -r line;
    do
        if [[ "$line" =~ $regexConfName ]]; then
            echo "找到匹配行：$line"
            if [[ "$line" =~ $regexKey1 ]] || [[ "$line" =~ $regexKey2 ]]; then
                echo "匹配行中包含关键字：$keyword1 or $keyword2"
                modified_line="$(echo "$line" | sed "s/\b$confname\b/$confname$namespace/g")"
                echo "$modified_line" >> "$outfile"
                continue
            fi
        fi
        echo "$line" >> "$outfile"
    done < "$infile"
}

function parseServiceList() {
    listfile="$1"
    sourcepath="$2"
    namespace="$3"
    outputpath="$4"
    container="$5"

    if [ -s "$listfile" ]; then
        while IFS= read -r line || [[ -n "$line" ]]
        do
            echo $line
            serviceFileName=$line
            namespace_conflicted_services $sourcepath $serviceFileName $namespace $outputpath $container
        done < "$listfile"
    fi    
}

function parseConfList() {
    listfile="$1"    
    namespace="$2"
    outputpath="$3"
    sourcepath="/usr/share/dbus-1/system.d/"

    if [ -s "$listfile" ]; then
        while IFS= read -r line || [[ -n "$line" ]]
        do
            echo $line
            confFileName=$line
            namespace_conflicted_confs $sourcepath $confFileName $namespace $outputpath
        done < "$listfile"
    fi  
}

function main() {
    systembuslist="$1"
    sessionbuslist="$2"
    conflist="$3"
    namespace="$4"
    container="$5" 

    if [ -s "$systembuslist" ]; then
        echo "Parsing system conflicted service list"
        parseServiceList $systembuslist $SYSTEM_BUS_SERVICE_PATH $namespace $OUTPUTPATH$SYSTEMSERVICEDEST $container
    else
        echo "No system conflicted service list exist"
    fi

    if [ -s "$sessionbuslist" ]; then
        echo "Parsing session conflicted service list"
        parseServiceList $sessionbuslist $SESSION_BUS_SERVICE_PATH $namespace $OUTPUTPATH$SESSIONSERVICEDEST $container
    else
        echo "No session conflicted service list exist"
    fi

    if [ -s "$conflist" ]; then
        echo "Parsing system conflicted conf list"
        parseConfList $conflist $namespace $OUTPUTPATH$SYSTEMCONFDEST
    else
        echo "No session conflicted service list exist"
    fi
}

main $@


