#!/bin/sh

# Copyright (c) ULBSD Project Team. All rights reserved.
# $Id: plasma_backup 6 2020-05-20 16:33:07Z sv $

# PROVIDE: plasma_backup
# REQUIRE: FILESYSTEM
# KEYWORD: shutdown
#
# Add the following to /etc/rc.conf to enable plasma_backup at shutdown time:
#
# plasma_backup_enable (bool):
#			Set it to "YES" to enable plasma_backup.
#			Set to "NO" by default.
# plasma_backup_count (positive decimal from 1 to 100):
#			Set it to maximum number of backups.
#			Set to 100 by default.

. /etc/rc.subr

name=plasma_backup
rcvar=plasma_backup_enable

start_cmd=":"
stop_cmd="${name}_stop"

load_rc_config $name

: ${plasma_backup_enable="NO"}
: ${plasma_backup_count="100"}

plasma_backup_stop()
{
    max_backup_count="100"
    backup_count="${max_backup_count}"

    if [ "${plasma_backup_count}" ] && [ ! "`/bin/echo "${plasma_backup_count}" | /usr/bin/tr -d '[0-9]'`" ]
    then
        backup_count="`expr -e 0${plasma_backup_count} + 0`"
        if [ "$backup_count" -gt "${max_backup_count}" ] || [ "$backup_count" -lt "1" ]
        then
            backup_count="${max_backup_count}"
        fi
    fi

    backup_count="`expr -e 0${backup_count} + 1`"

    /usr/bin/find /home /root -depth -name '.config' -exec /usr/bin/tar cPfz {}/plasma_backup_`/bin/date +'%Y%m%d_%H%M%S'`.tgz {}/plasma-org.kde.plasma.desktop-appletsrc {}/plasmarc {}/plasmashellrc \;
    /usr/bin/find /home /root -depth -name '.config' -exec /bin/sh -c "/bin/ls -1t {}/plasma_backup_* | /usr/bin/tail -n+${backup_count} | /usr/bin/xargs /bin/rm -f" \;
}

run_rc_command "$1"
