#!/bin/bash
# Runs as root (contest-restrictions-warning.service). While any contest
# restriction is off (after maintenance with contest-restrictions off), shows
# a red banner across the top of the screen, so that the proctors notice it.
# The banner has no title bar or close button, the team account cannot stop
# this process, and the banner comes back within seconds if its window is
# destroyed. It is redrawn every 15 seconds to stay above the other windows.
export DISPLAY=:0 XAUTHORITY=/var/run/lightdm/root/:0
off() {
    ! systemctl is-active --quiet firewall.service ||
    ! systemctl is-active --quiet usbguard.service ||
    [ -n "$(ls -A /etc/contest-restrictions/disabled 2>/dev/null)" ]
}
show() {
    width=$(xdpyinfo 2>/dev/null | awk '/dimensions/ {split($2, a, "x"); print a[1]}')
    [ -n "$width" ] || return
    xmessage -geometry "${width}x70+0+0" -buttons "" \
        -xrm "*overrideRedirect: true" \
        -fg white -bg red3 -fn "-*-helvetica-bold-r-*-*-34-*-*-*-*-*-*-*" \
        "CONTEST RESTRICTIONS ARE OFF ON THIS MACHINE - CALL THE STAFF" >/dev/null 2>&1 &
    pid=$!
    shown=$(date +%s)
}
pid=""
shown=0
while true; do
    if off && [ -e "$XAUTHORITY" ]; then
        if [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; then
            show
        elif [ $(( $(date +%s) - shown )) -ge 15 ]; then
            old=$pid
            show
            sleep 1
            kill "$old" 2>/dev/null
        fi
    elif [ -n "$pid" ]; then
        kill "$pid" 2>/dev/null
        pid=""
    fi
    sleep 3
done
