#!/bin/sh
# crossloop -- restart crossfire-server in case of a crash

# You should not edit this script! Instead, place any overrides into one of
# the configuration files.

# Set paths that are determined by the build system.
prefix="@prefix@"
exec_prefix="@exec_prefix@"

# Read configuration files.
for config_file in "@sysconfdir@/crossfire/crossloop.conf"; do
    if [ -r ${config_file} ]; then
        . ${config_file} && echo "===>>> Loaded '${config_file}'"
    fi
done

#### CONFIGURATION ####

# Full path to server binary.
CF_BIN=${CF_BIN:-"@bindir@/crossfire-server"}

# Additional flags to pass to the server.
CF_FLAGS=${CF_FLAGS:-"-d"}

# Directory to use for storing temporary runtime files. It is created if it
# does not exist. It should be dedicated to Crossfire, because it is saved
# in the event of a server crash.
CF_TMP=${CF_TMP:-"/tmp/crossfire"}

# Path to server log (default "$CF_TMP/crossfire.log").
CF_LOG=${CF_LOG:-"${CF_TMP}/crossfire.log"}

# Maximum number of restarts (set to zero to loop infinitely, default 100).
MAX_RESTART=${MAX_RESTART:-"100"}

# Directory for saving crash data.
CRASH_DIR=${CRASH_DIR:-"`dirname ${CF_TMP}`"}

# Send mail to server admins in case of a crash (comment out to disable).
#CRASH_MAIL="yourname@example.com"

#### END OF CONFIGURATION ####

# The current generation of the server.
generation=1

while [ ${MAX_RESTART} -ne ${generation} ]; do
    # Create folder to store temporary files if it doesn't exist.
    if [ ! -d ${CF_TMP} ]; then
        mkdir ${CF_TMP}
        chmod 700 ${CF_TMP}
    fi

    # Change to the ${CF_TMP} directory and start server.
    cd ${CF_TMP}
    echo "===>>> Starting server (generation ${generation})..."

    ${CF_BIN} ${CF_FLAGS} -tmpdir "${CF_TMP}" -log "${CF_LOG}"

    # If the server crashed and CRASH_DIR is set, save CF_TMP.
    if [ ${?} -ne 0 -a -n "${CRASH_DIR}" ]; then
        crash_dump="${CRASH_DIR}/crossfire-`date +%Y-%m-%d-%H:%M`.crash"
        mv ${CF_TMP} ${crash_dump}
        core_files=`ls ${crash_dump}/*core*`
        dumpfile="${crash_dump}/crash.log"
        cat << EOF > $dumpfile
Crossfire has terminated unexpectedly. Information about this crash is saved
in '${crash_dump}' on `hostname`.

`uname -a`

The following core dumps were found:

${core_files}

The following backtrace was generated by GDB:

`gdb ${CF_BIN} ${core_files} -batch`

If this crash occurs frequently or can be reliably reproduced, please file a
bug report with the full contents of this crash report.
EOF

        if [ -n "${CRASH_MAIL}" ]; then
            mail -s "Crossfire crash on `hostname`" "${CRASH_MAIL}" < $dumpfile
        fi
        echo "===>>> Crash info saved in $dumpfile"
    fi

    echo "===>>> Restarting server (type CTRL-C to quit)..."
    # Increment server generation.
    generation=`expr ${generation} + 1`

    # Wait for 10 seconds before restarting again.
    sleep 10
done
