#!/bin/sh

# For each Upstart Session Init, emit "rotate-logs" event, requesting
# the session Inits to rotate their logs. There is no user-daily cron.
#
# Doing it this way does not rely on System Upstart, nor
# upstart-event-bridge(8) running in the Session Init.
#
# Note that system-level Upstart logs are handled separately using a
# logrotate script.

[ -x /sbin/initctl ] || exit 0

for file in /run/user/*/upstart/sessions/*.session
do
    [ -f "$file" ] || continue
    [ -h "$file" ] && continue

    file_uid=$(stat -c %u "$file")
    [ -n "$file_uid" ] || continue

    session=$(grep \
	    "^UPSTART_SESSION=unix:abstract=/com/ubuntu/upstart-session/[0-9][0-9]*/[0-9][0-9]*$" \
	    "$file" 2>/dev/null || true)
    [ -n "$session" ] || continue

    session_uid=$(echo "$session" | cut -d\/ -f5)
    [ -n "$session_uid" ] || continue

    # Don't allow a user to spoof logrotation for another user.
    [ "$file_uid" = "$session_uid" ] || continue

    env -i "$session" /sbin/initctl emit rotate-logs >/dev/null 2>&1 || true
done
