#!/bin/bash

function checkStatus() {
        if [ -d "/proc/"$1 ]; then
                eval "TEST=1"
        else
                eval "TEST=0"
        fi
}

function starter() {
    local CURRENT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

    cd $BINPATH

    mkdir -p "$LOGS_PATH"

    TRACE_BEGIN_STRING="SIGSEGV"
    TRACE_FILE="$LOGS_PATH/"$SCREEN_NAME"_trace.log"
    ERR_FILE="$LOGS_PATH/"$SCREEN_NAME"_error.log"
    SYSLOG="$LOGS_PATH/"$SCREEN_NAME"_system.log"
    SYSERR="$LOGS_PATH/"$SCREEN_NAME"_system.err"
    LINKS_FILE="$LOGS_PATH/"$SCREEN_NAME"_crash_links.link"

    $CURRENT_PATH/starter $SERVERBIN $GDB "$CONFIG" "$SYSLOG" "$SYSERR" $GDB_ENABLED
}


function restarter() {
    local CURRENT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
    cd $BINPATH

    mkdir -p "$LOGS_PATH"

    TRACE_BEGIN_STRING="SIGSEGV"
    TRACE_FILE="$LOGS_PATH/"$SCREEN_NAME"_trace.log"
    ERR_FILE="$LOGS_PATH/"$SCREEN_NAME"_error.log"
    SYSLOG="$LOGS_PATH/"$SCREEN_NAME"_system.log"
    SYSERR="$LOGS_PATH/"$SCREEN_NAME"_system.err"
    LINKS_FILE="$LOGS_PATH/"$SCREEN_NAME"_crash_links.link"

    if [ ! -f $TRACE_FILE ]; then
        touch $TRACE_FILE
    fi

    while :
    do
            PID=$(cat $SERVERPID)
            checkStatus $PID
            if [ $TEST -eq 0 ]; then
                    DATE=$(date)
                    echo "Restarting $SCREEN_NAME Core blizz($DATE)"
                    if [ $GDB_ENABLED -eq 1 ]; then
                            echo "GDB enabled"
                            grep -B 10 -A 1800 "$TRACE_BEGIN_STRING" "$SYSLOG" >> "$TRACE_FILE"
                            cat "$SYSERR" > "$ERR_FILE"
                            screen -A -m -d -S $SCREEN_NAME "$CURRENT_PATH/starter" $SERVERBIN $GDB "$CONFIG" "$SYSLOG" "$SYSERR" 1
                    fi

                    if [ $GDB_ENABLED -eq 0 ]; then
                            echo "GDB disabled"
                            screen -A -m -d -S $SCREEN_NAME "$CURRENT_PATH/starter" $SERVERBIN null "$CONFIG" null null 0
                    fi
            fi

            sleep 15
    done
}
