# To use it you need to include:
# /opt/multiwan/lib/bash/common_vars

function to_syslog {
    # Usage example: to_syslog "info" "all is good."
    # $SYSLOG_FACILITY is global variable.
    # $SYSLOG_TAG is global variable.
    # $LOGGER is global variable.
    local SYSLOG_SEVERITY="$1"
    local SYSLOG_MSG="$2"

    case "$SYSLOG_SEVERITY" in
    "info"|"warning"|"error"|"debug")
        # ${SYSLOG_SEVERITY^^} convert string to uppercase.
        $LOGGER -p "$SYSLOG_FACILITY.$SYSLOG_SEVERITY" -t $SYSLOG_TAG "${SYSLOG_SEVERITY^^}: $SYSLOG_MSG"
    ;;
    *)
        return 1
    ;;
    esac
}

function is_openwrt_os {

    if ! $GREP -q "OpenWrt" /proc/version; then
        return 1
    fi

    return 0
}

function is_debian_os {

    if ! $GREP -q "Debian" /proc/version; then
        return 1
    fi

    return 0
}

function is_astra_os {

    if ! $GREP -q "AstraLinux" /proc/version; then
        return 1
    fi

    return 0
}

function is_used_systemd {

    if [[ ! -f $SYSTEMD_NOTIFY ]]; then
        # OS is not using systemd.
        return 1
    fi

    return 0
}

function get_daemon_pid {

    local DAEMON_PID=""
    local OUT=""
    local RESULT=""
    local DAEMON_PID_FILE=""

    DAEMON_PID_FILE="$1"
    if [[ ! -f $DAEMON_PID_FILE ]]; then
        return 1
    fi

    OUT=$($CAT $DAEMON_PID_FILE)
    RESULT=$?
    if (( $RESULT != 0 )); then
        return 1
    fi
    DAEMON_PID="$OUT"

    $ECHO "$DAEMON_PID"
    return 0
}

function check_multiwan_pid_file {
    local RESULT=""
    local DAEMON_PID=""
    local PID_CMD_LINE_BEGINNING=""
    PID_FILE="$1"

    DAEMON_PID=$(get_daemon_pid "$PID_FILE")
    RESULT=$?
    if (( $RESULT != 0 )); then
        $ECHO "Failed to get PID from $PID_FILE"
        return 1
    fi

    if [[ ! -f /proc/$DAEMON_PID/cmdline ]]; then
        $ECHO "Process with PID from $PID_FILE does not exist."
        return 1
    fi

    PID_CMD_LINE_BEGINNING=$(tr '\0' ' ' < /proc/$DAEMON_PID/cmdline | cut -d' ' -f1-2)
    if ! [[ "$PID_CMD_LINE_BEGINNING" == "$MULTIWAN_CMD_LINE_BEGINNING" ]]; then
        $ECHO "Process with PID from $PID_FILE is not multiwan."
        return 1
    fi

    $ECHO $DAEMON_PID
    return 0
}

function create_run_dir {
    local RUN_DIR="$1"

    if [[ -d "$RUN_DIR" ]]; then
        return 0
    fi

    $MKDIR -p $RUN_DIR 2> /dev/null
    RESULT=$?
    if (( $RESULT != 0 )); then
        return 1
    fi
    return 0
}
