#!/bin/sh

#  Exit codes from starti:
#  0  MinimServer or MinimWatch interactive process started successfully or was already running
#     (for MinimServer, this might also require starting the background process)
#  1  Error starting interactive process
#
#  Exit codes from starti auto:
#  0  MinimServer or MinimWatch interactive process started successfully or didn't need to be started
#  1  Error starting interactive process
#
#  Exit codes from starti check:
#  1  Unexpected error
#  2  MinimWatch interactive process is not running
#  3  MinimWatch interactive process is running

ws="server"
#ws="watch"

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

# check whether the MinimWatch interactive 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 [ -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" = "auto" -a "watch" = "${ws}" ]; then
    if "${SCRIPTDIR}/setup" autostart_enabled; then
        # MinimWatch autostart always starts the interactive process at login
        shift
    else
        exit 0
    fi
fi

ICONDISPLAY=1
if [ "$1" = "auto" ]; then
    # check whether the daemon processes are running
    "${MINIMDIR}/bin/startd" check || exit 0
    shift
elif [ "$1" = "check" ]; then
    if [ "server" = "${ws}" ]; then
        echo "Internal error" 1>&2
        exit 1
    fi
    # check whether the MinimWatch interactive process is running
    if _check; then
        exit 3
    else
        exit 2
    fi
elif [ "${ws}" = "server" ]; then
    "${MINIMDIR}/bin/startd" check
    CHECKRC=$?
    if [ ${CHECKRC} -eq 2 ]; then
        # need to start MinimServer daemon process to survive user logout
        ICONDISPLAY=0
     elif [ ${CHECKRC} -ne 0 ]; then
        echo "Internal error" 1>&2
        exit 1
    fi
else
    if _check; then
        # MinimWatch is already running
        exit 0
    fi
fi

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

# start the required MinimServer processes
if [ "server" = "${ws}" ]; then
    env >"${MINIMDIR}/data/minim${ws}-display.env"
    if [ ${ICONDISPLAY} -eq 0 ]; then
        # start MinimServer daemon process and ServerWatch icon display process
        "${MINIMDIR}/bin/startd" --set "watch.iconDisplay=true" "$@"
    else
        # tell MinimServer daemon process to start ServerWatch process
        echo "showicon" | "${MINIMDIR}/bin/mscript" >/dev/null
    fi
    exit
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 MinimWatch as a background process and update pid file
_launch() {
    # prepare to launch
    trap _exit EXIT
    trap _term TERM
    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=trayIcon --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=trayIcon --nohup ${MINIMOPTS} "$@" >>"${OUTFILE}" 2>&1 &
        fi
        mpid=$!
        echo $mpid > "${MINIMPIDFILE}"
        rm -f "${MINIMSTARTFILE}"
        wait $mpid
        LAUNCHRC=$?
        mpid=
        rm -f "${MINIMPIDFILE}"
        [ ${LAUNCHRC} -ne 23 ] && return ${LAUNCHRC}
        RELAUNCH="--relaunch"
    done
}

touch "${MINIMSTARTFILE}"

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

# launch MinimWatch and continue
_launch "$@" &

# check to see whether MinimWatch 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

exit 0
