#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2014, 2015, 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 *****
# 

if [ x`whoami` != xzimbra ]; then
  echo "Error: must be run as zimbra user"
  exit 1
fi

if [ ! -x /opt/zimbra/common/bin/mysql ]; then
  echo "Error: mariadb not available"
  exit 1
fi

if [ x"$1" = "x-h" ]; then
  echo "Usage"
  echo "zmmytop [-h] [-r]"
  echo "-h: Display this message"
  echo "-r: Connect as root user (Default: connect as Zimbra user)"
  echo "--[no]color : Use color Default: use color if available"
  echo "--delay <seconds>: How long between display refreshes. Default: 5"
  echo "--batch : In batch mode, mytop runs only once, does not clear the screen, and places no limit on the number of lines it will print."
  echo "--[no]header : Display header"
  echo "--[no]idle : Specify if you want idle (sleeping) threads to appear in the list."
  echo "--[no]resolve : If you have skip-resolve set on MySQL (to keep it from doing a reverse"
  echo "                DNS lookup on each inbound connection), mytop can replace IP addresses with hostnames"
  echo "                Default: noresolve"
  exit 0
fi

source `dirname $0`/zmshutil || exit 1
zmsetvars

if [ -x "/opt/zimbra/common/bin/mytop" ]; then
  if [ x"$1" = "x-r" ]; then
    shift
    /opt/zimbra/common/bin/mytop -u root -S $mysql_socket -p $mysql_root_password $@
  else
    /opt/zimbra/common/bin/mytop -u $zimbra_mysql_user -S $mysql_socket -p $zimbra_mysql_password $@
  fi
fi
