#!/bin/bash

# Copyright 2008-2009 Anibal Monsalve Salazar <anibal@debian.org>
#
# 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; either version 2 of the License, or (at your
# option) any later version.
#
# 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

set -e
set -u
#set -x

shopt -s nocasematch

declare data
declare from
declare key
declare keys
declare msd
declare rank
declare group
declare msg_id
declare name
declare tr_class
declare regex
declare eof

declare -i count=0

declare -r regex_1="^(.*);(.*);(.*);(.*)$"

data=$( < names.txt )
msd_data=$( < msd-sorted.txt )

while read line
do
    if [[ "$line" =~ $regex_1 ]]
    then
        from="${BASH_REMATCH[1]}"
        keys="${BASH_REMATCH[2]}"
        msg_id="${BASH_REMATCH[3]}"
        url="${BASH_REMATCH[4]}"
    else
        echo error: \"$line\"
        exit 1
    fi

    count=$(( count + 1 ))
    name=${from%% <*}

    msd=""
    msd=$( 
        for key in $keys
        do
            regex="^ *([[:digit:]]+) [0-9A-F]{8} $key *(.*)$"
            while :
            do
                if ! read msd_line
                then
                    echo 999
                    break
                fi

                if [[ "$msd_line" =~ $regex ]]
                then
                    echo ${BASH_REMATCH[2]}
                    break
                fi
            done <<< "$msd_data"
        done
    )
    msd=${msd//$'\n'/ }

    rank=""
    rank=$(
        for key in $keys
        do
            regex="^ *([[:digit:]]+) [0-9A-F]{8} $key *(.*)$"
            while :
            do
                if ! read msd_line
                then
                    echo 999
                    break
                fi

                if [[ "$msd_line" =~ $regex ]]
                then
                    echo ${BASH_REMATCH[1]}
                    break
                fi
            done <<< "$msd_data"
        done
    )
    rank=${rank//$'\n'/ }

    echo "$rank;$msd;$keys;$count;$name"

done <<< "$data" > rank.txt

exit 0
