#!/bin/sh

ACTION=status
case "$1" in
    (r) ACTION=restart ;;
    (s) ACTION=status ;;
    (restart|start|stop|status) ACTION=$1 ;;
    (l|log)
        SERVER="$2"
        shift 2
        exec journalctl -b --no-hostname -f -u entangle@$SERVER "$@"
    ;;
    (reload)
        rm -f /run/systemd/generator/entangle.stamp
        exec systemctl daemon-reload
    ;;
esac
if [ "$#" -ge 1 ]; then shift; fi

SERVERS=
while [ -n "$1" ]; do
    SERVERS="$SERVERS entangle@$1"
    shift
done

if [ -z "$SERVERS" ]; then
    systemctl list-units -a --plain --no-legend 'entangle@*' | awk '{
        if ($4 == "running") {
            printf("%-20s %s\n", substr($1, 10, length($1) - 17), $4)
        } else {
            printf("\033[1;31m%-20s %s\033[0m\n", substr($1, 10, length($1) - 17), $4)
        }
    }'
else
    systemctl $ACTION $SERVERS
fi
