#!/bin/sh
set -e

case "$1" in
    configure)
        systemd-sysusers terractl.conf
        systemd-tmpfiles --create terractl.conf
        if [ -d /run/systemd/system ]; then
            systemctl daemon-reload || true
        fi
        # Let the terraria group read the servers' journal (LogNamespace=terraria)
        terractl journal-access || true
        # Servers running from before 0.0.11 still log to the system journal until
        # restarted, so 'terractl attach' and 'cmd' can't show their output yet.
        if [ -n "$2" ] && dpkg --compare-versions "$2" lt 0.0.11 && [ -d /run/systemd/system ]; then
            running=$(systemctl list-units --plain --no-legend --state=active 'terraria@*.service' | awk '{print $1}')
            if [ -n "$running" ]; then
                echo "Restart running Terraria servers so they use their new journal:"
                for unit in $running; do echo "  sudo systemctl restart $unit"; done
            fi
        fi
        # Running instances are not restarted; they pick up changes on their next start.
        ;;
esac

exit 0
