#!/bin/bash
#
# @@@ START COPYRIGHT @@@
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# @@@ END COPYRIGHT @@@

# This script cleans up the log files of various components
if [ -e $SQ_PDSH ]; then
   L_PDSH="/usr/bin/pdsh $MY_NODES "
else
   L_PDSH=
fi

function usage() {
   prog=`basename $0` 
   echo ""
   echo "$prog { all | dcs | rest | core }"
   echo "    all  --- Remove files from core, dcs and rest logs folder"
   echo "    dcs  --- Remove files from $DCS_INSTALL_DIR/logs folder"
   echo "    rest --- Remove files from $REST_INSTALL_DIR/logs folder"
   echo "    core --- Remove log files residing in $TRAF_HOME/logs folder"
}

function core_logs() {
 if [[ ! -z $L_PDSH ]]; then
   $L_PDSH "rm -f ${TRAF_HOME}/logs/*.err"
   $L_PDSH "rm -f ${TRAF_HOME}/logs/*.log"
   $L_PDSH "rm -f ${TRAF_HOME}/logs/*log.[0-9]*"
   $L_PDSH "rm -f ${TRAF_HOME}/sql/scripts/stdout_*"
 else
   rm -f ${TRAF_HOME}/logs/*
   rm -f ${TRAF_HOME}/sql/scripts/stdout_*
 fi
}

function dcs_logs() {
 if [[ ! -z $L_PDSH ]]; then
   $L_PDSH "rm -f ${DCS_INSTALL_DIR}/logs/*.log"
   $L_PDSH "rm -f ${DCS_INSTALL_DIR}/logs/*.log.[0-9]*"
   $L_PDSH "rm -f ${DCS_INSTALL_DIR}/logs/*.out"
   $L_PDSH "rm -f ${DCS_INSTALL_DIR}/logs/*.out.[0-9]*"
 else
   rm -f ${DCS_INSTALL_DIR}/logs/*
 fi
}

function rest_logs() {
 if [[ ! -z $L_PDSH ]]; then
   $L_PDSH "rm -f ${REST_INSTALL_DIR}/logs/*.log"
   $L_PDSH "rm -f ${REST_INSTALL_DIR}/logs/*.log.[0-9]*"
   $L_PDSH "rm -f ${REST_INSTALL_DIR}/logs/*.out"
   $L_PDSH "rm -f ${REST_INSTALL_DIR}/logs/*.out.[0-9]*"
 else
   rm -f ${REST_INSTALL_DIR}/logs/*
 fi
}

function all_logs() {
   core_logs
   dcs_logs
   rest_logs
}

if [ ! -z ${TRAF_HOME} ]; then
   case "$1" in 
      core)
        core_logs
        ;;
      dcs)
        dcs_logs
        ;;
      rest)
        rest_logs
        ;;
      all)
        all_logs
        ;;
      *)
        usage
        exit 1
   esac
fi
exit 0
