#!/bin/sh

ACTION=status
case "$1" in
    (r) ACTION=restart ;;
    (s) ACTION=status ;;
    (restart|start|stop|status) ACTION=$1 ;;
    (l|log|logs)
        if [ $# -eq 1 ]; then SERVER="*"; shift 1; else SERVER="$2"; shift 2; fi
        journalctl --no-hostname -u entangle@"$SERVER" -o json "$@" | python3 -c "if 1:
        import sys, json, time
        fmtmap = {'3': '\x1b[01;31m', '4': '\x1b[01;35m', '6': '\x1b[0m', '7': '\x1b[01;30m'}
        for entry in sys.stdin:
            try:
                entry = json.loads(entry)
                dt = time.strftime('%Y-%m-%d %H:%M:%S',
                    time.localtime(int(entry['__REALTIME_TIMESTAMP']) * 1e-6))
                print(f\"\x1b[37m{dt} {entry['SYSLOG_IDENTIFIER']}[{entry['_PID']}]: \"
                      f\"{fmtmap.get(entry['PRIORITY'], '')}{entry['MESSAGE']}\x1b[0m\")
                if 'TRACEBACK' in entry: print(entry['TRACEBACK'])
            except:
                print(f'\x1b[01;31m<error in entry: {entry}>\x1b[0m')
        "
        exit 0
    ;;
    (reload)
        rm -f /run/systemd/generator/entangle.stamp
        systemctl try-restart entangle-late-generator
        systemctl daemon-reload
    ;;
esac
if [ "$#" -ge 1 ]; then shift; fi

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

if [ -z "$SERVERS" -a "$ACTION" = status ]; then
    UNITS=$(systemctl list-units -a --plain --no-legend 'entangle@*')
    EXIT=0
    while read LINE; do
        set -- $LINE
        SVC="${1%.service}"
        STAT="$4"
        if [ "$STAT" != running ]; then
            printf '%-20s \033[1;31m%s\033[0m\n' "${SVC#entangle@}" "$STAT"
            EXIT=1
        else
            printf '%-20s \033[32m%s\033[0m\n' "${SVC#entangle@}" "$STAT"
        fi
    done <<EOF
$UNITS
EOF
    exit $EXIT
fi

if [ -z "$SERVERS" ]; then
    UNITS=$(systemctl list-units -a --plain --no-legend 'entangle@*')
    while read LINE; do
        set -- $LINE
        SERVERS="$SERVERS $1"
    done <<EOF
$UNITS
EOF
fi

exec systemctl $ACTION $SERVERS
