#!/bin/sh
# Copyright (c) 2007-2019 Andrew Ruthven <andrew@etc.gen.nz>
# This code is hereby licensed for public consumption under the GNU GPL v3.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# Run mythtv-status to update the MOTD.

NAME=mythtv-update-motd

# Debian style
[ -r /etc/default/mythtv-status ] && . /etc/default/mythtv-status
# Fedora style
[ -r /etc/sysconfig/mythtv-status ] && . /etc/sysconfig/mythtv-status

# Support the old RUN variable
[ x$UPDATE_MOTD = x ] && UPDATE_MOTD=$RUN

if [ x$UPDATE_MOTD != xyes -o -f /var/lib/mythtv-status/motd_update_disabled ]
then
  exit
fi

WORKFILE=/run/motd
TEMPFILE=/run/motd.mythtv-status

if [ -d /etc/update-motd.d ]
then
  # We want to generate file which only contains the MythTV Status
  # as a snippet in /etc/update-motd.d will cat this file.
  #
  # Current (as of 2019-01-1) Debian and Ubuntu releases use this
  # method.

  WORKFILE=/run/motd.mythtv-status
  TEMPFILE=${WORKFILE}.new
else
  # We are going to generate an motd file to be used for the system,
  # with the previous content first, then the MythTV Status.

  STUBFILE=/run/motd.orig

  if [ -f /etc/os-release ]
  then
    DISTRO=$(awk -F= '$1 == "ID" { print $2 }' /etc/os-release)
  else
    DISTRO='unknown'
  fi

  if [ $DISTRO = 'fedora' ]
  then
    WORKFILE=/etc/motd
    STUBFILE=/etc/motd.stub
    TEMPFILE=/etc/motd.mythtv-status
  fi

  # Just incase someone has removed their motd file.
  [ -f $WORKFILE ] || touch $WORKFILE
  # Keep the original content around.
  [ -f $STUBFILE ] || cp $WORKFILE $STUBFILE

  # If the tempfile is less than 15 minutes old, object, otherwise
  # we'll assume that something went wrong and remove it.
  if [ -f $TEMPFILE ]; then
      AGE=$(stat -c "%Z" $TEMPFILE);
    if (( $AGE > $(date +'%s') - 900 ))
    then
        echo "I think another $NAME is running."
        exit 1
    fi
  fi

  # Have whatever the system motd contains before the MythTV content
  cp $STUBFILE $TEMPFILE
fi

# Support the old ARGS variable
[ x$UPDATE_MOTD_ARGS = x ] && UPDATE_MOTD_ARGS=$ARGS

ret=0
mythtv-status $UPDATE_MOTD_ARGS -h $HOST >> $TEMPFILE || ret=$?
if [ $ret -eq 0 -o $ret -eq 1 ]; then
  if [ ! -f $TEMPFILE ]; then
    echo My temporary file has gone away, failed.
    exit 1
  else
    mv $TEMPFILE $WORKFILE
  fi
else
  # Something else went wrong, remove the temp file.
  rm $TEMPFILE
  exit 1
fi

# Local Variables:
# sh-basic-offset: 2
# End:
