#!/usr/bin/bash

notify ()
{
    [ -n "${LAUNCHED_BY_SYSTEMD}" ] && systemd-notify "$*"
}

die ()
{
    echo "$*" 1>&2
    notify --status="$*"
    exit 1
}

readonly conf_file=/etc/enyx-inspector/main.conf

[ -f "${conf_file}" ] || die "missing \"${conf_file}\""
# shellcheck source=/dev/null
. ${conf_file}

echo "Using ${address:?"missing 'address' configuration key"}:${port:?"missing 'port' configuration key"}"

core_descriptions=${core_descriptions:-/usr/share/enyx-cores-descriptions}

# Prefer HFP over PFP
if [ -n "${mock_tree}" ]; then
    [ -f "${mock_tree}" ] || die "No such mock: ${mock_tree}"
    mock_options=(-Djna.nosys=true
                  -Dtapestry.execution-mode=mock
                  -Denyx.agent.mock.tree-file="${mock_tree}")
elif [ -d /dev/hfp ] || [ -d /dev/enyx/hfp ]; then
    readonly driver=hfp
elif [ -d /dev/enyx ]; then
    readonly driver=pfp
else
    die 'Neither PFP or HFP driver have been detected'
fi


readonly status_file="${RUNTIME_DIRECTORY:-.}/enyx-inspector.status"

rm -f "${status_file}"
/usr/bin/java \
    -Djava.security.egd=file:/dev/urandom \
    -Duser.language=en \
    -Duser.region=US \
    -Denyx.port="${port}" \
    -Denyx.address="${address}" \
    -Denyx.driver="${driver}" \
    -Denyx.agent.cores-desc.dir="${core_descriptions}" \
    -Denyx.agent.status-file="${status_file}" \
    -classpath /usr/share/enyx-inspector/:/usr/share/enyx-inspector/enyx-inspector-war-exec.jar \
    org.apache.tomcat.maven.runner.Tomcat7RunnerCli \
    "${mock_options[@]}" \
    -serverXmlPath /usr/share/enyx-inspector/server.xml &

trap "kill %1 >/dev/null 2>&1" EXIT

# Wait timeout_s for the process to create a status file
timeout_s=60
while true; do
    # Timeout expired
    [ "${timeout_s}" -ne 0 ] || die 'Timeout expired'

    # Check if the process is still alive
    jobs %1 >/dev/null 2>&1 || die 'Process died on startup'

    # Break if status file is provided
    [ -f "${status_file}" ] && break

    ((timeout_s-=1))
    sleep 1
done

# Check if an error occured (i.e. the status file is not empty)
[ -s "${status_file}" ] && die 'Process failed to start'

# Inform systemd that the inspector is up if required
notify --ready

# Wait for the enyx-inspector to terminate
wait
