#!/bin/bash
# @file
# @brief CII Postinstall
#
# @copyright
#   SPDX-FileCopyrightText: 2025 European Southern Observatory (ESO) @n
#   SPDX-License-Identifier: LGPL-3.0-only

# Installed by ELT CII Postinstall
# Called by logrotate (/etc/logrotate.d/elt-log)
#
# Rescues logfiles when log-rotate is about to delete them.
# Supports max-capacity to prevent filling up the disk.
#
# Usage: <cfg> <log>
#   cfg: "<dir>, <cap>, <fmt>"
#     dir: /var/log/elt/attic
#     cap: none|500M|2.5G|unlimited
#     fmt: gzip|uncompressed
#   log: /var/log/elt/elt-20251231-1409.log
#
# Rationale for using a dedicated attic directory:
#  - do not bloat the original dir (/var/log/elt)
#  - ensure shrink operates only on files owned by us
#
# This tool gets its config fully from the cli. This
# way the config can be kept in the logrotate conf file.
# Therefore, all args are mandatory on every call.

#echo $0: Called with $@ >> /tmp/attic.out

usage_error() { echo "Usage: \"<dir>, <cap>, <fmt>\" <log>" >&2; exit 2; }

cfg=$1
log=$2
IFS=, read dir cap fmt <<< $cfg

case $cap in
  0|none)     exit 0 ;;    # attic not wanted
  unlimited)  shrink= ;;   # shrinking not wanted
  *)          shrink=$(echo $cap|numfmt --from=iec 2>/dev/null) || usage_error ;;
esac

[ $dir ]      || usage_error
mkdir -p $dir || usage_error # fails when file (or broken symlink, etc.) is given

[ $log ]    || usage_error
[ -e $log ] || usage_error
logname=$(basename $log)     # elt-20251231-1409.log

case $fmt in
  gzip)         gzip -c $log > $dir/$logname.gz ;;
  uncompressed) cp      $log   $dir ;;
  *)            usage_error ;;
esac

# auto-purge
if [ $shrink ]; then
  table=  # 567345  /var/log/elt/attic/elt-20251231-140908.log.gz
  table() { table=$(du -b $dir/*.gz 2>/dev/null); [ -n "$table" ]; }
  total() { echo "$table" | cut -f1 | paste -sd+ | bc; }
  first() { echo "$table" | cut -f2 | head -n1; }
  while table && [ $(total) -gt $shrink ]; do rm "$(first)" || break; done
fi
