#!/bin/sh

#
# Analyze a rancid configuration file, and extracts equipment names
# and types. Then, from each equipment configuration file, extract
# then exact model.
#
# Syntax :
#	list-rancid <dbfile> <confdir>	> <output-file>
#
# History :
#   2004/06/08 : pda/jean : design
#   2008/07/07 : pda      : add hp
#   2008/12/15 : jean     : add pattern of types to ignore
#   2010/09/27 : pda      : case where a file does not exist yet
#

if [ $# != 2 ]
then
    echo "usage: $0 <dbfile> <confdir>" >&2
    exit 1
fi

DB="$1"
DIR="$2"

IGNORE="^[a-zA-Z0-9][-a-zA-Z0-9.]*:wrapper\."

fetch_model_cisco ()
{
    sed -n "/^!Chassis type:/s/!Chassis type: \([^ ]*\).*/\1/p" "$1"|head -n1
}

fetch_model_hp ()
{
    sed -n "/^;Chassis type:/s/;Chassis type: \([^ ]*\).*/\1/p" "$1"|head -n1
}

fetch_model_juniper ()
{
    sed -n "/^# Chassis/s/.* \([^ ]*\)$/\1/p" "$1"|head -n1
}

fetch_model_server ()
{
    sed -n "/^! uname: \([^ ]*\)$/s//\1/p" "$1"|head -n1
}

IFS=":;"
grep "[:;]up$" $DB | egrep -v "$IGNORE" |
    while read eq type up
    do
	f="$DIR/$eq"
	if [ ! -s "$f" ]
	then
	    echo "Missing or empty configuration file for '$eq'" >&2
	else
	    case "$type" in
		cisco)
		    model=`fetch_model_cisco "$DIR/$eq"`
		    ;;
		hp)
		    model=`fetch_model_hp "$DIR/$eq"`
		    ;;
		juniper)
		    model=`fetch_model_juniper "$DIR/$eq"`
		    ;;
		server)
		    model=`fetch_model_server "$DIR/$eq"`
		    ;;
		*)
		    echo "Unsupported type '$type' for '$eq' in $DB" >&2
		    exit 1
		    ;;
	    esac
	    echo "$eq $type $model"
	fi
    done
