#!/bin/sh

# Copyright (c) 2010-2013 Aleksey Cheusov <vle@gmx.net>
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

set -e

LC_ALL=C
export LC_ALL

. pipestatus

: ${LMDBG_S2M_DIR:=/usr/pkg/libexec/lmdbg}
: ${LMDBG_M2S_DIR:=/usr/pkg/libexec/lmdbg}

s2m_cmd=${LMDBG_S2M_DIR}/lmdbg-s2m
m2s_cmd=${LMDBG_M2S_DIR}/lmdbg-m2s

usage () {
    cat <<'EOF'
usage: lmdbg-sort [OPTIONS] [files...]
OPTIONS:
  -h           display this help
  -V           display version
  -f <field>   sorting key, valid values are: peak, max, allocs, leaks, num.
               This option is mandatory.
EOF
}

version (){
cat <<'EOF'
lmdbg-grep 1.3.0
EOF
}

while getopts hVf: f; do
    case $f in
	h)
	    usage
	    exit 0;;
	V)
	    version
	    exit 0;;
	f)
	    field=$OPTARG;;
	'?')
	    usage
	    exit 1;;
    esac
done
shift $(expr $OPTIND - 1)

if test -z "$field"; then
    usage
    exit 1
fi

number_first (){
    awk -v field="$field:" '
$1 == "info" && $2 != "modulestat" {
   print "4000000000", $0
   next
}
{
   value = 0
   for (i=1; i <= NF; ++i){
      if ($i == field){
         value = $(i+1)
         break
      }
   }
   print value, $0
}
' "$@"
}

no_number (){
    sed 's/^[^ ]* //'
}

order_peak='r'
order_max='r'
order_allocs='r'
order_leaks='r'
order_num=''

if test -z "$order"; then
    eval order='$order_'"$field"
fi

runpipe0 \
    "$m2s_cmd" "$@" '|' \
    number_first '|' \
    sort -k1${order}n '|' \
    no_number '|' \
    "$s2m_cmd"
