#!@BASH_PATH@
#
# Copyright 2011-2023 the Pacemaker project contributors
#
# The version control history for this file may have further details.
#
# This source code is licensed under the GNU General Public License version 2
# or later (GPLv2+) WITHOUT ANY WARRANTY.
#

hosts=
group=
kill=0
while true; do
    case "$1" in
	-x) set -x; shift;;
	-w) for h in $2; do
		hosts="$hosts -w $h";
	    done
	    shift; shift;;
	-g) group=$2; shift; shift;;
	--kill) kill=1; shift;;
	--kill-only) kill=2; shift;;
	"") break;;
	*) echo "unknown option: $1"; exit 1;;
    esac
done

if [ x"$group" = x -a x"$hosts" = x ]; then
    group=$CTS_GROUP
fi

if [ x"$hosts" != x ]; then
    echo `date` ": Cleaning up hosts:"
    target=$hosts
elif [ x"$group" != x ]; then
    echo `date` ": Cleaning up group: $group"
    target="-g $group"
else
    echo "You didn't specify any nodes to clean up"
    exit 1
fi
cluster-helper --list bullet $target

if [ $kill != 0 ]; then
    echo "Cleaning processes"

    # Bah. Force systemd to actually look at the process and realize it's dead
    cluster-helper $target -- "service corosync stop" &> /dev/null &
    cluster-helper $target -- "service pacemaker stop" &> /dev/null &

    cluster-helper $target -- "killall -q -9 corosync pacemakerd pacemaker-attrd pacemaker-based pacemaker-controld pacemaker-execd pacemaker-fenced pacemaker-remoted pacemaker-schedulerd dlm_controld gfs_controld" &> /dev/null
    cluster-helper $target -- 'kill -9 `pidof valgrind`' &> /dev/null

    if [ $kill == 2 ]; then
	exit 0
    fi
fi

#logrotate -f $cluster_rotate
echo "Cleaning files"

log_files=""
log_files="$log_files 'messages*'"
log_files="$log_files 'localmessages*'"
log_files="$log_files 'cluster*.log'"
log_files="$log_files 'corosync.log*'"
log_files="$log_files 'pacemaker.log*'"
log_files="$log_files '*.journal'"
log_files="$log_files '*.journal~'"
log_files="$log_files 'secure-*'"

state_files=""
state_files="$state_files 'cib.xml*'"
state_files="$state_files 'valgrind-*'"
state_files="$state_files 'cib-*'"
state_files="$state_files 'core.*'"
state_files="$state_files 'cts.*'"
state_files="$state_files 'pe*.bz2'"
state_files="$state_files 'fdata-*'"

for f in $log_files; do
    cluster-helper $target -- "find /var/log -name '$f' -exec rm -f \{\} \;"
done

for f in $state_files; do
   cluster-helper $target -- "find /var/lib -name '$f' -exec rm -f \{\} \;"
done

cluster-helper $target -- "find /dev/shm -name 'qb-*' -exec rm -f \{\} \;"
cluster-helper $target -- "find @CRM_BLACKBOX_DIR@ -name '*-*' -exec rm -f \{\} \;"
cluster-helper $target -- "find /tmp -name '*.valgrind' -exec rm -f \{\} \;"

cluster-helper $target -- 'service rsyslog restart' > /dev/null  2>&1
cluster-helper $target -- 'systemctl restart systemd-journald.socket' > /dev/null  2>&1
cluster-helper $target -- logger -i -p daemon.info __clean_logs__

#touch $cluster_log
echo `date` ": Clean complete"
