#!/bin/sh
# The base's start, with the settings a deploy passes as AGENTENV_SETTING_<NAME>, their defaults artifact.toml's:
# init applies the time zone for every program and starts supervisord, which runs xvfb at the resolution, and with-x
# runs a program, the XFCE session first, once X answers.
set -eu
resolution="${AGENTENV_SETTING_RESOLUTION:-1280x800}"
width="${resolution%%x*}" height="${resolution#*x}"
echo "$resolution" | grep -Eqx '[1-9][0-9]{0,4}x[1-9][0-9]{0,4}' && [ "$width" -le 32767 ] && [ "$height" -le 32767 ] \
    || { echo "resolution is <width>x<height>, each 1 to 32767 pixels, not '$resolution'" >&2; exit 2; }
case "${1:-}" in
    init)
        timezone="${AGENTENV_SETTING_TIMEZONE:-UTC}"
        [ -f "/usr/share/zoneinfo/$timezone" ] || { echo "timezone '$timezone' isn't in /usr/share/zoneinfo" >&2; exit 2; }
        export TZ="$timezone"
        exec /usr/bin/supervisord -c /etc/supervisor/supervisord.conf
        ;;
    xvfb)
        exec Xvfb "$DISPLAY" -screen 0 "${resolution}x24" -nolisten tcp -ac
        ;;
    with-x)
        shift
        for _ in $(seq 100); do xdpyinfo >/dev/null 2>&1 && break; sleep 0.1; done
        exec "$@"
        ;;
    *)
        echo "usage: start-desktop init|xvfb|with-x <command>" >&2; exit 2
        ;;
esac
