#!/sbin/openrc-run
# Copyright 2008-2025 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2 or later

: "${EMACS:=/usr/bin/emacs}"
: "${EMACS_OPTS:=--fg-daemon}"
: "${EMACS_SHELL=/bin/bash}"
: "${EMACS_START:=/usr/libexec/emacs/emacs-wrapper.sh}"
: "${EMACS_TIMEOUT:=30}"

description="Start an Emacs server running in the background"

command=${EMACS_START}
command_args=${EMACS_OPTS}
command_background=true
command_user=${RC_SVCNAME##*.}
directory="~${command_user}"
pidfile=/var/run/${RC_SVCNAME}.pid
retry=TERM/${EMACS_TIMEOUT}/KILL/5

depend() {
    after dbus
}

start_pre() {
    if [ "${command_user}" = "${RC_SVCNAME}" ]; then
        eerror "You have to create an init script for each user:"
        eerror "ln -s emacs /etc/init.d/emacs.<user>"
        return 1
    fi

    if ! id -u "${command_user}" >/dev/null; then
        eerror "${command_user}: No such user"
        return 1
    fi

    # EMACS could be a microemacs variant that ignores the -batch option
    # and would therefore hang, waiting for user interaction.
    # Redirecting stdin and unsetting TERM and DISPLAY will cause most
    # of them to exit with an error.
    if [ "$(unset TERM DISPLAY; ${EMACS} -batch -q --no-site-file \
            --eval "(princ (fboundp 'daemonp))" </dev/null)" != t ]; then
        eerror "${EMACS} does not support running as a daemon"
        return 1
    fi

    SHELL=${EMACS_SHELL:-$(awk -F: \
        "\$1 == \"${command_user}\" { print \$7 }" /etc/passwd)}
    export SHELL EMACS

    # XDG_RUNTIME_DIR points to /run/user/0 which is not writable for us
    # Unset it, otherwise Emacs would try to create its server socket there
    unset XDG_RUNTIME_DIR
}
