#!/bin/sh
#
# ------------------------------------------------------------------
#  sh_proc_memory_sort.sh
# 
#  February 2014, Ajey Bharadwaj A
#  June     2014, Ajey Bharadwaj A (CSCup55952)
#	Changes Done : Set executable bit for user, group and others.
#
#  Copyright (c) 2010-2014 by Cisco Systems, Inc.
#  All rights reserved.
# ------------------------------------------------------------------

# Get the output of the executed command.
output=$(/pkg/bin/$1);

# Check whether the first 5 lines are empty or not
header=$(echo "$(echo "$output" | head -n 5)");
        
if [ -n "$header" ]; then
    # If first 5 lines are not empty then the data is sorted. Just echo it.
    echo "$output";
else
    # Check whether the first 10 lines are empty or not.
    header_one_location=$(echo "$(echo "$output" | head -n 10)");
    if [ -n "$header_one_location" ]; then
        # If not empty then remove first 5 lines and print the next 2 line.
        # The 2 lines contain the Column name and seperator line.
        echo "$(echo "$output" | head -n 7 | tail -n 2)";
        # Sort the output based on the memory in descending order.
        # Since the sort command by default uses /tmp and /tmp has very less
        #     space, using /dev/shm as first option and 
        #     /tmp as second option to perform the sorting.
        echo "$(echo "$output" | tail -n +8 | sort -n -k5 -r --temporary-directory=/dev/shm --temporary-directory=/tmp)";
    fi
fi
