#!/bin/bash

#
#    Copyright (c) 2020 SManSoft <http://www.smansoft.com/>
#                       Sergey Manoylo <info@smansoft.com>
#

FE_DESC="SM File Exchanger";
FE_HOME="/opt/fe/file_exchanger-0.0.11.11-Linux-x64";

SRVS_EXEC="$FE_HOME/bin/sm_file_send_srvs";
CLNS_EXEC="$FE_HOME/bin/sm_file_send_clns";

PIDDIR="/var/run";

if [ $UID -eq 0 ]; then
    SRVS_PID="$PIDDIR/sm_file_send_srvs.pid";
    CLNS_PID="$PIDDIR/sm_file_send_clns.pid";

    SRVS_PID_ROOT="";
    CLNS_PID_ROOT="";
else
    SRVS_PID="$PIDDIR/user/$UID/sm_file_send_srvs.pid";
    CLNS_PID="$PIDDIR/user/$UID/sm_file_send_clns.pid";

    SRVS_PID_ROOT="$PIDDIR/sm_file_send_srvs.pid";
    CLNS_PID_ROOT="$PIDDIR/sm_file_send_clns.pid";
fi;

test -d "$FE_HOME" || exit 0;
test -x "$SRVS_EXEC" || exit 0;
test -x "$CLNS_EXEC" || exit 0;

. /lib/lsb/init-functions

function kill_daemon()
{
    pid_file="$1";
    pid_file_0="$2";
    if [ ! -z $pid_file_0 ] && [ -f $pid_file_0 ]; then
        log_failure_msg "error killing the daemon (ROOT): $FE_DESC";
        exit 1;
    fi;
    if [ -f $pid_file ]; then
        pid=$(cat $pid_file);
        kill $pid;
        if [ $? -ne 0 ]; then
            log_failure_msg "error killing the process: pid = $pid";
            exit 1;
        fi;
    else 
        log_failure_msg "file isn't found pid_file = $pid_file";
        exit 1;
    fi;
    return;
}

function start_daemon()
{
    daemon_exec="$1";
    pid_file="$2";
    pid_file_0="$3";
    if [ ! -z $pid_file_0 ] && [ -f $pid_file_0 ]; then
        log_failure_msg "error starting the daemon (ROOT): $FE_DESC";
        exit 1;
    fi;
    if [ -f $pid_file ]; then
        return;
    fi;
    $daemon_exec "--daemon" "--pidfile=$pid_file";
    if [ $? -ne 0 ]; then
        log_failure_msg "error starting the daemon: $FE_DESC";
        exit 1;
    fi;
    return;
}

case $1 in
    start)
        log_daemon_msg "Starting" "$FE_DESC";
        start_daemon "$SRVS_EXEC" "$SRVS_PID" "$SRVS_PID_ROOT";
        start_daemon "$CLNS_EXEC" "$CLNS_PID" "$CLNS_PID_ROOT";
        log_end_msg 0;
        ;;
    stop)
        log_daemon_msg "Stopping" "$FE_DESC";
        kill_daemon "$SRVS_PID" "$SRVS_PID_ROOT";
        kill_daemon "$CLNS_PID" "$CLNS_PID_ROOT";
        log_end_msg 0;
        ;;
    restart)
        log_daemon_msg "Restarting" "$FE_DESC";
        kill_daemon "$SRVS_PID" "$SRVS_PID_ROOT";
        kill_daemon "$CLNS_PID" "$CLNS_PID_ROOT";
        sleep 1;
        start_daemon "$SRVS_EXEC" "$SRVS_PID" "$SRVS_PID_ROOT";
        start_daemon "$CLNS_EXEC" "$CLNS_PID" "$CLNS_PID_ROOT";
        log_end_msg 0;
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}";
        exit 1;
        ;;
esac

exit 0;
