Automatically starting weechat in tmux via systemd --user

Aug 3, 2016   #weechat  #systemd  #tmux  #debian  #debian jessie 

Motivation

I use weechat for IRC and as a XMPP/Jabber bouncer with bitlbee. It runs inside a tmux session on a Debian Jessie host.

Until today I just started it manually on every reboot (doesn’t happen often and needs manual intervention for disk crypto anyway), but since I love reboot-save systems, here is how I fixed that:

Debian Jessie comes with systemd as its init system, so we’ll use that to start weechat on boot. I want weechat to run as my user, so I could a) write a systemd system unit with User=clemens or b) write a unit that runs in a systemd user session under my user. I chose the latter option, since that allows the user to configure the unit without root previleges.

weechat.service

The unit itself is pretty straightforward. Save the following to ~/.config/systemd/user/weechat.service:

[Unit]
Description=Weechat IRC Client (in tmux)

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/tmux -2 -u new-session -d -s weechat /usr/bin/weechat
ExecStop=/usr/bin/tmux kill-session -t weechat

[Install]
WantedBy=default.target

Note the Type=oneshot and RemainAfterExit=yes which are needed because the command will exit directly and the tmux server manages the weechat process outside of systemd’s cgroups.

Enable systemd user session

The first problem I encountered with the systemd user session was that there simply was no such session on my Debian.

Normally logind and pam start a systemd user session for every user on login, but on Debian you first have to install the optional dependency libpam-systemd to make this happen.

Also we want weechat to start directly on boot, so we’ll need the user session to also be spawned on boot and not only when the user logs in. We tell logind to do this by running sudo loginctl enable-linger $USER.

Now reboot.

Enable the unit

You should now have a systemd user session running:

$ pgrep -fau $USER "systemd"
711 /lib/systemd/systemd --user

Now you can finally enable and start the unit:

$ systemctl --user enable weechat
$ systemctl --user start weechat

If everything went right, you can now attach to your weechat using tmux attach -d -t weechat

tl;dr

$ mkdir -p ~/.config/systemd/user/
$ cat << EOF > ~/.config/systemc/user/weechat.service
[Unit]
Description=Weechat IRC Client (in tmux)

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/tmux -2 -u new-session -d -s weechat /usr/bin/weechat
ExecStop=/usr/bin/tmux kill-session -t weechat

[Install]
WantedBy=default.target
EOF
$ sudo apt-get install libpam-systemd
$ sudo loginctl enable-linger $USER
$ reboot
$ systemctl --user enable weechat
$ systemctl --user start weechat