#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2010, 2013, 2014, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 

source /opt/zimbra/bin/zmshutil || exit 1

usage() {
    echo "Usage: $0 [-k <keep count>] [-h] [-l] [-p]"
    echo ""
    echo "    -h|--help    Help/usage information"
    echo "    -k|--keep    Number of archived copies of zmstat data to retain."
    echo "    -l|--list    Generate a listing of log dates archived."
    echo "    -p|--purge   Purge ALL archived zmstats data."
    echo ""
    exit
}

zmsetvars


while [ $# -gt 0 ]
do
    case $1 in
        -h | --help)
            usage
            ;;
        -k | --keep)
            shift
            zmstat_max_retention=$1
            ;;
        -l | --list)
            listArchives=TRUE
            ;;
        -p | --purge)
            purgeAll=TRUE
            ;;
        *)
            echo "ERROR: Unknown option $1"
            usage
            ;;
    esac
    shift
done


cd /opt/zimbra/zmstat 2>/dev/null
if [ $? -ne 0 -o "${PWD}" != "/opt/zimbra/zmstat" ]
then
    echo "ERROR: Cannot change to the zmstats log directory /opt/zimbra/zmstat."
    exit -1
fi


if [ "${listArchives}x" == "TRUEx" ]
then
    if [ "`ls -1A | egrep '^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$' | wc -l`" -gt 0 ]
    then
        /bin/ls -d1 [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]
    fi
elif [ "${purgeAll}x" == "TRUEx" ]
then
    DIR_LIST=`find . -type d -print | egrep '^\./[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$' | sort -r | sed -e "s%./%%"`
    for d in ${DIR_LIST}
    do
        echo "Deleting ${d} zmstat archive."
        /bin/rm -rf ${d}
    done
elif [ ${zmstat_max_retention:-"0"} -gt 0 ]
then
    DIR_LIST=`find . -type d -print | egrep '^\./[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]$' | sort -r | sed -e "1,${zmstat_max_retention}d ; s%./%%"`

    for d in ${DIR_LIST}
    do
        echo "Deleting ${d} zmstat archive."
        /bin/rm -rf ${d}
    done
else
    echo "WARNING: zmstat_max_retention is set to 0 or is undefined.  No zmstat data has been pruned."
fi

