aboutsummaryrefslogtreecommitdiffstats
path: root/assistant.sh
blob: 30216ddad75e894f9236f7b139a3904e57125a31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/bash
# desktop-assistant: start, stop, restart or check the daemon.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# assistant.sh start|stop|restart|status
#
# stop: SIGTERM any running assistant.py, SIGKILL after 10 s. start: run it
# in its own session, detached from the terminal, logging where the
# Hyprland autostart does; does nothing for one already running. restart:
# stop, then start. status: the process, the socket and the log's tail;
# exit 1 when it is down.

set -eu

dir=$(cd "$(dirname "$0")" && pwd)
log="${XDG_RUNTIME_DIR:?not in a login session}/desktop-assistant.log"
pat='^\S*python3 (-u )?\S*assistant\.py$'   # not a --test run

kill_wait() {
    pkill -u "$USER" -f "$1" || return 0
    for _ in $(seq 50); do
        pgrep -u "$USER" -f "$1" >/dev/null || return 0
        sleep 0.2
    done
    pkill -KILL -u "$USER" -f "$1" && sleep 0.5 || true
}

running() { pgrep -u "$USER" -f "$1" >/dev/null; }

stop() {
    kill_wait "$pat"
}

start() {
    cd "$dir"
    running "$pat" || setsid -f python3 -u "$dir/assistant.py" >>"$log" 2>&1 </dev/null
    sleep 0.5
    status
}

status() {
    local pid
    if pid=$(pgrep -u "$USER" -of "$pat"); then
        echo "assistant: running"
        ps -o pid=,etime=,rss= -p "$pid" | awk '{ printf "  pid %s, up %s, %d MB\n", $1, $2, $3 / 1024 }'
    else
        echo "assistant: not running"
    fi
    [ -S "$XDG_RUNTIME_DIR/desktop-assistant.sock" ] && echo "socket: present" || echo "socket: missing"
    echo "log: $log"
    tail -n 5 "$log" 2>/dev/null | sed 's/^/  /'
    [ -n "$pid" ]
}

case "${1:-}" in
    start) start ;;
    stop) stop ;;
    restart) stop; start ;;
    status) status ;;
    *) echo "usage: $0 start|stop|restart|status" >&2; exit 2 ;;
esac