#!/bin/bash

function read_key(){
    local file=$1
    local section=$2
    local key=$3

    python3 -c "
import configparser;
config = configparser.ConfigParser(allow_no_value=True);
config.optionxform = str;
config.read('${file}');
print(config.get('${section}','${key}', fallback=''));
"
}

function write_key(){
    local file=$1
    local section=$2
    local key=$3
    local value=$4

    python3 -c "
import configparser;
config = configparser.ConfigParser(allow_no_value=True);
config.optionxform = str;
config.read('${file}');
if not config.has_section('${section}'):
    config.add_section('${section}')
config.set('${section}', '${key}', '${value}')
with open('${file}', 'w') as f:
    config.write(f, space_around_delimiters=False)
"
}

function read_section(){
    local file=$1
    local section=$2

    python3 -c "
import configparser;
config = configparser.ConfigParser(allow_no_value=True);
config.optionxform = str;
config.read('${file}');
if config.has_section('${section}'):
    for option in config.options('${section}'):
        print(f\"{option}={config.get('${section}', option, fallback='')}\");
"
}

function add_component(){
    local file=$1
    local value=$2

    cat ${file} | grep -Pq "^Component.\d=${value}\$"
    if [ $? -ne 0 ];then
        cat ${file}  | grep -Pq "Component.\d=\$"
        if [ $? -eq 0 ];then
            local t_key=$(cat ${file} | grep -P "Component.\d=\$" | head -n 1 )
            sed -i "s/${t_key}/${t_key}${value}/g" ${file}
            return
        fi
        comps=$(read_section "${file}" "ComponentManager")
        COMP_NUM=0
        if [[ -n "$comps" ]]; then
            COMP_NUM=$(echo "${comps}" | wc -l)
        fi
        COMP_NUM=$(($COMP_NUM + 1))
        write_key "${file}" "ComponentManager" "Component.${COMP_NUM}" "${value}"
    fi
}

CONF=/etc/codesyscontrol/CODESYSControl.cfg
CONF_USER=/etc/codesyscontrol/CODESYSControl_User.cfg
# 根据实际修改name
can_name=can

write_key "${CONF}" "CmpSocketCanDrv" "ScriptPath" "/opt/codesys/scripts/"
write_key "${CONF}" "CmpSocketCanDrv" "ScriptName" "rts_set_baud.sh"
write_key "${CONF}" "CmpSocketCanDrv" "CmpSocketCanDrv" "${can_name}"

add_component "${CONF}" "CmpOpenSSL"
add_component "${CONF}" "CmpCAACanL2"
add_component "${CONF}" "CmpCAASdoServer"
add_component "${CONF}" "CmpCAASdoClient"
add_component "${CONF}" "CmpSocketCanDrv"

sed -i 's/Component.*=CmpGwClientCommDrvTcp/;&/' /${CONF_USER}