#!/bin/sh

set -eu

if [ -n "${EXAMMODE_SESSION:-}" ]; then
  exit 0
fi

HOSTNAME=$(hostname)
TIMESTAMP=$(date +"%Y%m%d-%H%M%S.%N")
CONF_DIR="${HOME}/.config/puavomenu"

# While this can be changed, it's not advisable to do so unless
# you have a really good reason for it
USER_PROGS="${HOME}/.local/share/applications"

if [ ! -d "${CONF_DIR}" ]; then
    mkdir -p "${CONF_DIR}"
fi

# Remove old socket files (they live in $XDG_RUNTIME_DIR now)
(find "${CONF_DIR}" -name "socket*" -type s -delete) || true

# Development or production mode? Development mode is the default.
DEV_MODE=1

if [ $# -gt 0 ]; then
    if [ "$1" = "--prod" ]; then
        DEV_MODE=0
    fi
fi

# use "&" in the end to put to background so that we register immediately
# as being ready
while true; do
    if [ $DEV_MODE -eq 1 ]; then
        # Development mode. Assume this is a local copy of the
        # puavo-os/opinsys-os repo.
        python3 ./puavomenu \
            --res_dir "./res" \
            --menu_dir "../../rules/puavomenu/templates" \
            --user_conf "${CONF_DIR}" \
            --socket "${XDG_RUNTIME_DIR}/puavomenu_dev" \
            "$@" || {
            status=$?
            if [ $status -eq 2 ]; then
                # Resolution has changed, relaunch. Dimensions might
                # be different this time.
                continue
            fi
            exit $status
        }
        break
    else
        # Production mode. Use real paths.
        python3 /opt/puavomenu/puavomenu \
            --prod \
            --autohide \
            --log "/tmp/puavomenu_${TIMESTAMP}.log" \
            --res_dir "/opt/puavomenu/res" \
            --menu_dir "/etc/puavomenu/" \
            --user_conf "${CONF_DIR}" \
            --socket "${XDG_RUNTIME_DIR}/puavomenu" || {
            status=$?
            if [ $status -eq 2 ]; then
                # Resolution has changed, relaunch. Dimensions might
                # be different this time.
                continue
            fi
            exit $status
        }
        break
    fi
done &
