#!/bin/sh
set -eu
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
operation=${1:-attach}
directory=${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}}/cclshd-$(id -u)
if [ ! -d "$directory" ]; then mkdir -m 700 "$directory"; fi
socket=${CCLSH_DAEMON_SOCKET:-$directory/server.sock}
case "$operation" in
    run)
        exec env CCLSH_SERVER_MODE=run CCLSH_SERVER_SOCKET="${2:-$socket}" \
            "$repo/scripts/cclsh-sbcl"
        ;;
    start) exec "$repo/cclsh-session" start "$socket" "$repo/scripts/cclshd" ;;
    status|stop) exec "$repo/cclsh-session" "$operation" "$socket" ;;
    attach)
        if [ "$#" -gt 0 ]; then shift; fi
        exec "$repo/cclsh-session" attach "$socket" "$repo/scripts/cclsh-sbcl" "$@"
        ;;
    *)
        echo 'usage: cclshd start|stop|status|attach [shell arguments]' >&2
        exit 2
        ;;
esac
