#!/bin/bash

function update_config(){
    local t_codesys=$(dpkg -l | grep -E ed-codesys-[0-9]{3} | awk '{print $2}')
    local t_need_qt=$((${t_codesys} & 1))
    if [ ${t_need_qt} -eq 1 ];then
        dpkg -l | grep ed-qt5-v1 > /dev/null
        if [ $? -ne 0 ];then
            echo "[Error] Need to install ed-qt5-v1."
            exit 1
        fi
        rm -rf /usr/lib/aarch64-linux-gnu/libQt5*
        ldconfig
        local f_config="/etc/init.d/codesyscontrol"
        # local line=`sed -n "/CONFIGFILE=/=" ${f_config}`
        local line=`sed -n "/do_start () {/=" ${f_config}`
        # line=`expr $line + 1`
        grep -q "^    export XAUTHORITY=" ${f_config}
        if [ $? -ne 0 ];then
            sed -i "${line}a\    export XAUTHORITY=/home/pi/.Xauthority" ${f_config}
        fi
        grep -q "^    export DISPLAY=" ${f_config}
        if [ $? -ne 0 ];then
            sed -i "${line}a\    export DISPLAY=:0" ${f_config}
        fi
        grep -q "^    . /etc/profile.d/qt5.sh" ${f_config}
        if [ $? -ne 0 ];then
            sed -i "${line}a\    . /etc/profile.d/qt5.sh" ${f_config}
            sed -i "${line}a\    sleep 10" ${f_config}
        fi
        systemctl daemon-reload
    fi
}

update_config
