#!/bin/sh

#  Exit codes from startd:
#  0  MinimServer background process started successfully or was already running
#  1  Error starting MinimServer background process
#
#  Exit codes from startd check:
#  0  MinimServer background process is running
#  1  Unexpected error
#  2  MinimServer background process is not running

ws="server"
#ws="watch"

if [ "server" = "${ws}" ]; then
    WS="Server"
else
    WS="Watch"
fi

# check whether the MinimServer background process is running
_check() {
    pid="$(cat "${MINIMPIDFILE}" 2>/dev/null)"
    if [ -n "$pid" ]; then
        cmdline="$(cat /proc/$pid/cmdline | tr '\0' ' ' 2>/dev/null)"
        if [ -n "$(echo "$cmdline" | grep m${ws}\\.jar)" ]; then
            return 0
        fi
    fi
    return 1
}

SCRIPTNAME="$(readlink -f "$0")"
SCRIPTDIR="$(dirname "${SCRIPTNAME}")"
SCRIPTDIRBASE="$(basename "${SCRIPTDIR}")"
if [ "${SCRIPTDIRBASE}" != "bin" ]; then
    echo "Script location error: ${SCRIPTNAME}" 1>&2
    exit 1
fi
INSTALLDIR="$(dirname "${SCRIPTDIR}")"
MINIMDIR="$(dirname "${INSTALLDIR}")"
MINIMDIRBASE="$(basename "${MINIMDIR}")"
if [ "${MINIMDIRBASE}" != "minim${ws}" ]; then
    echo "Script location error: ${SCRIPTNAME}" 1>&2
    exit 1
fi
MINIMPIDFILE="${MINIMDIR}/data/minim${ws}.pid"
MINIMSTARTFILE="${MINIMDIR}/data/minim${ws}.start"

if [ "$1" = "init" ]; then
    if [ -x "${MINIMDIR}/etc/startd-init.sh" ]; then
        "${MINIMDIR}/etc/startd-init.sh" || exit
    fi
fi

if [ -f "${MINIMDIR}/etc/minimstart.conf" ]; then
    tab=$(printf '\t')
    JAVA="$(grep "^java[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
    JAVAOPTS="$(grep "^javaopts[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
    JAVALANG="$(grep "^javalang[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
    MINIMLANG="$(grep "^minimlang[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
    LANGFILE="$(grep "^langfile[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
    LANGKEY="$(grep "^langkey[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
    OUTFILE="$(grep "^outfile[ $tab]*=" "${MINIMDIR}/etc/minimstart.conf" | head -n 1 | sed 's/\r//' | cut -f2- -d'=' | sed 's/^ *//')"
fi
if [ -z "${OUTFILE}" ]; then
    OUTFILE="${MINIMDIR}/data/minim${ws}-out.log"
fi

if [ "$1" = "init" ]; then
    shift
fi

if [ "$1" = "wait" ]; then
    wait="true"
    shift
fi

if [ "$1" = "check" ]; then
    if [ "watch" = "${ws}" ]; then
        echo "Internal error" 1>&2
        exit 1
    fi
    # check whether the MinimServer background process is running
    if _check; then
        exit 0
    else
        exit 2
    fi
fi

if [ "watch" = "${ws}" ]; then
    echo "MinimWatch cannot run as a daemon background process" 1>&2
    exit 1
fi

# perform migration actions if needed
"${SCRIPTDIR}/setup" migrate && echo "Saved configuration has been migrated"

# check whether the MinimServer background process is running
"$0" check
checkrc=$?
if [ $checkrc -ne 2 ]; then
    exit $checkrc
fi

# handle exit
_exit() {
    #echo "Running exit handler"
    rm -f "${MINIMSTARTFILE}"
    rm -f "${MINIMPIDFILE}"
    #echo "Exit handler complete"
}

# handle SIGTERM
_term() {
    #echo "Caught SIGTERM signal"
    MPID=$mpid
    if [ -n "${MPID}" -a -e "/proc/${MPID}" ]; then
        kill ${MPID} 2>/dev/null
        max_wait_time=9
        wait_time=0
        while :
        do
            [ -e "/proc/${MPID}" ] || break
            [ ${wait_time} -eq ${max_wait_time} ] && break
            wait_time=$((wait_time+1))
            sleep 1
        done
    fi
    #echo "SIGTERM processing complete"
}

# start MinimServer as a background process and update pid file
_launch() {
    # prepare to launch
    trap _exit EXIT
    trap _term TERM
    unset DISPLAY
    cd "${MINIMDIR}/data"
    if [ -f "${MINIMDIR}/etc/minim${ws}.defaults" ]; then
        MINIMOPTS="--defaults \"${MINIMDIR}/etc/minim${ws}.defaults\""
    fi
    if [ -n "$JAVALANG" ]; then
        export LANG="$JAVALANG"
    fi

    # relaunch protocol
    RELAUNCH=""
    while :
    do
        if [ -n "${JAVA}" ]; then
            JAVAX="${JAVA}"
        else
            JAVAX=java
            for f in "${MINIMDIR}"/lib/minimjre*.dir "${MINIMDIR}"/libext/minimjre*.dir
            do
                [ ! -e "$f.jmdel" ] && [ -x "$f/jre/bin/java" ] && JAVAX="$f/jre/bin/java"
            done
        fi
        if [ -n "${MINIMLANG}" ]; then
            MINIM_LANG=${MINIMLANG};
        elif [ -n "${LANGFILE}" -a -n "${LANGKEY}" ]; then
            MINIM_LANG="$(grep "^${LANGKEY}" "${LANGFILE}" | head -n 1 | cut -f2- -d'=' | sed 's/^ *//')"
        fi
        if [ -z "${RELAUNCH}" ]; then
            LD_LIBRARY_PATH="${MINIMDIR}/libsys" MINIM_LANG="${MINIM_LANG}" "${JAVAX}" ${JAVAOPTS} -jar "${MINIMDIR}/lib/m${ws}.jar" --launchrc --set watch.view=log --nohup ${MINIMOPTS} "$@" >"${OUTFILE}" 2>&1 &
        else
            LD_LIBRARY_PATH="${MINIMDIR}/libsys" MINIM_LANG="${MINIM_LANG}" "${JAVAX}" ${JAVAOPTS} -jar "${MINIMDIR}/lib/m${ws}.jar" --launchrc ${RELAUNCH} --set watch.view=log --nohup ${MINIMOPTS} "$@" >>"${OUTFILE}" 2>&1 &
        fi
        mpid=$!
        echo $mpid > "${MINIMPIDFILE}"
        rm -f "${MINIMSTARTFILE}"
        wait $mpid
        LAUNCHRC=$?
        mpid=
        if [ ${LAUNCHRC} -ne 23 ]; then
            if [ -x "${MINIMDIR}/etc/startd-exit.sh" ]; then
                "${MINIMDIR}/etc/startd-exit.sh"
            fi
            rm -f "${MINIMPIDFILE}"
            return ${LAUNCHRC}
        else
            rm -f "${MINIMPIDFILE}"
        fi
        RELAUNCH="--relaunch"
    done
}

touch "${MINIMSTARTFILE}"

# set pid file to a valid process with a command line
echo "$$" > "${MINIMPIDFILE}"

if [ -n "$wait" ]; then
    # launch MinimServer and wait
    _launch "$@"
else
    # launch MinimServer and continue
    _launch "$@" &

    # check to see whether MinimServer is running
    while :
    do
        [ -f "${MINIMSTARTFILE}" ] || break
        sleep 1
    done
    if ! _check; then
        if [ -s "${OUTFILE}" ]; then
            cat "${OUTFILE}" 1>&2
        else
            echo "Failed to start Minim${WS}" 1>&2
        fi
        exit 1
    fi
fi

exit 0
