#! /bin/sh

# If /sys/fs/pstore exists, and is not empty, the move
# the files to /var/log/pstore (creating it if necessary)

# The files in pstore are typically files from panic, but depending
# on kernel configuration, may be from normal reboots as well.
# Depending on kernel config, they may be compressed (usually lzip
# compression, although others can be selected).
# This script doesn't worry about the type of the file, we just
# save them, and log them to syslog.  cl-support will pick them up.

# The files are moved because in most implementations, they use EFI
# variable space in the BIOS, and can cause failures due to lack of
# space, as well as to allow support to get panic info.

# To ensure we don't explode the size of /var/log, we keep no more than
# 1MB worth of files, performing the check whenever we move files.
# This is typically enough for hundreds of files.
# If files need to be removed, we always save the 10 newest and 10 oldest
# (by filesystem date, not necessarily the date in the pstore file)
# and then remove enough older files to reach no more than 1MB of storage.

# This script runs once at boot from the cumulus-pstore.service

pstore=/sys/fs/pstore
logstore=/var/log/pstore 
oldest=10 newest=10 # number of oldest and newest to keep if too large
maxspace=1024 # max space in 1KB to use for saved pstore files

[ -d $pstore ] || exit 0

cd $pstore || exit 0

# assumes 4.1 - 4.19 kernel semantics of only files in $pstore, no
# subdirs, symlinks, etc.
files=$(ls 2>/dev/null)

[ -z "$files" ] && exit 0

nfiles=$(ls 2>/dev/null | wc -l)

logger -s -t pstore Found ${nfiles} files in /sys/fs/pstore from reboot or panic

umask 077

[ -d $logstore ] || {
	mkdir -p $logstore || exit 1
	chown root.root $logstore
	}

mv ./* ${logstore}/ || exit 1

cd ${logstore} || exit 1

used=$(du -sk .| sed 's/\s.*//')

[ $used -lt $maxspace ] && exit 0

files_old=$(ls -t -1 | sed 1,${newest}d)
[ -z "$files_old" ] && exit 0 # shouldn't happen, but...
nfiles=$(ls -1 $files_old | wc -l)
nfiles=$(( nfiles - oldest ))
[ $nfiles -le 0 ] && exit 0
files_to_remove=$(ls -t -1 | sed -n 1,${nfiles}p)
[ -z "$files_to_remove" ] && exit 0 # shouldn't happen, but...

logger -s -t pstore Removing $nfiles /var/log/pstore log files because ${used}KB used
logger -s -t pstore Removed /var/log/pstore files: "$files_to_remove"

rm -f $files_to_remove
