#!/bin/bash

main() {
    need_restart=0
    local original_str=`cat /opt/lnxall_app/bin/emsd_startup.sh | grep "check_program_and_recover proto_forward"`
    if [ -n "$original_str" ] && [[ "$original_str" != *"-L 0"* ]] ; then
        echo "original_str:"$original_str
        quoted_str='    '`echo $original_str | sed 's/"[^"]*/& -l 0 -L 0/'`
        echo "quoted_str:"$quoted_str
        sed -i "s/$original_str/$quoted_str/" "/opt/lnxall_app/bin/emsd_startup.sh"
        need_restart=1
    fi
    original_str=`cat /opt/lnxall_app/bin/emud_startup.sh | grep "check_program_and_recover emu_lc"`
    if [ -n "$original_str" ] && [[ "$original_str" != *"-L 0"* ]] ; then
        echo "original_str:"$original_str
        quoted_str='    '`echo $original_str | sed 's/"[^"]*/& -l 0 -L 0/'`
        echo "quoted_str:"$quoted_str
        sed -i "s/$original_str/$quoted_str/" "/opt/lnxall_app/bin/emud_startup.sh"
        need_restart=1
    fi
    #
    local ssd_dir="/mnt/ssd"
    local mounted=`mount | grep $ssd_dir | wc -l`
    if [ "$mounted" -eq 0 ]; then
        echo "ssd is not mounted"
    else
        echo "ssd is mounted"
        #
        local database_dir="/opt/lnxall_app/app/database"
        if [ -L $database_dir ]; then
            echo "database is already linked"
        else
            need_restart=1
            [ -e "$ssd_dir/database" ] && rm -rfv "$ssd_dir/database"
            systemctl stop emud
            systemctl stop emsd
            mv -v $database_dir $ssd_dir && \
            ln -sv $ssd_dir/database $database_dir && \
            echo "database is linked"
        fi
    fi
    #
    if [ "$need_restart" -gt 0 ]; then
        res=$(systemctl is-enabled emsd | grep -wc "enabled")
        if [ $res -gt 0 ]; then
            echo "emsd restart"
            systemctl restart emsd
        fi
        #
        res=$(systemctl is-enabled emud | grep -wc "enabled")
        if [ $res -gt 0 ]; then
            echo "emud restart"
            systemctl restart emud
        fi
    fi
}

main