#! /bin/bash

# logrotate-friendly-log-pipe <output-log-file>
# https://gist.github.com/praiskup/18f290b549a990c966b64e500797e714
#
# Pipe logs to the <output-log-file>.  Reopen the file upon the SIGHUP signal.
#
# This is especially useful when a multi-process Lighttpd server is used (with
# the 'server.max-workers = N' option), and use of Cronolog is not desirable:
# https://redmine.lighttpd.net/projects/1/wiki/Server_max-workerDetails
#
# Background story: https://pagure.io/copr/copr/issue/2001

logfile=$1

if test -z "$logfile"; then
    echo "usage: $0 <logfile>"
    exit 1
fi

cmd="$0 $*"
shell_pid=$$

quit()
{
  set -x ; kill "$cat_pid" ; wait ; exit 0
}

trap ':' HUP
trap 'quit' INT
trap 'quit' TERM
trap 'quit' USR1

# Wait for 'cat' to quit.  SIGHUP interrupt keeps cycling.
while :; do
    exec >> "$logfile"
    echo "=== start: $cmd ==="
    cat < /proc/$shell_pid/fd/0 &
    cat_pid=$!
    wait
    status=$?
    # ksh gives us 257 here
    test $status -ne 129 && test $status -ne 257 && break
    kill "$cat_pid"
    wait
done
