#!/usr/bin/bash

if [ "$(/usr/bin/id -u)" -ne 0 ]; then
  echo "You are not root"
  exit 1
fi

enable_motd() {
  /bin/systemctl enable update-motd.timer
  /bin/rm -f /var/lib/update-motd/disabled
}

disable_motd() {
  touch /var/lib/update-motd/disabled
  /bin/systemctl disable update-motd.timer
  test -f /etc/motd.d/99-rocky && /bin/rm /etc/motd.d/99-rocky
}

check_disabled() {
  if [ -e /var/lib/update-motd/disabled ]; then
    exit 0
  fi
}

main_update_motd() {
  if [ -d /etc/update-motd.d ]; then
    files_located=$(shopt -s nullglob dotglob; echo /etc/update-motd.d/*)
    TMPFILE=$(mktemp --tmpdir=/var/lib/update-motd/)
    if [ -f /etc/motd.head ]; then
      cat /etc/motd.head >> "$TMPFILE"
    fi
    if (( ${#files_located} )); then
      # Should we just use ${files_located}?
      #for scr in /etc/update-motd.d/*[^~,]; do
      for scr in ${files_located}; do
        # no rpmnew or rpmold files
        if [[ "$scr" =~ \.rpm* ]]; then continue ; fi
        # must be a file and executable, no symlinks
        if [ -f "$scr" ] && [ -x "$scr" ]; then
          TMPPART=$(mktemp --tmpdir motd.partXXX)
          if (timeout 30s "$scr" > "$TMPPART"); then
            cat "$TMPPART" >> "$TMPFILE"
          fi
          rm -f "$TMPPART"
        fi
      done
    fi
    if [ -f /etc/motd.tail ]; then
      cat /etc/motd.tail >> "$TMPFILE"
    fi
    /bin/cp "$TMPFILE" /etc/motd.d/99-rocky
  fi
}

case "$1" in
  --enable)
    enable_motd
    exit 0;;
  --disable)
    disable_motd
    exit 0;;
  '') ;;
  *)
    echo "Supported options: --disable | --enable"
    exit 1;;
esac

check_disabled
main_update_motd
