#!/bin/bash

TIME="time_real %e : time_user %U : time_sys %S\nmem_avg %K : mem_max %M : mem_faults_major %F : mem_faults_minor %R\nio_fsin %I : io_fsout %O : io_sockin %r : io_sockout %s : io_signals %k\nexit: %x"
DISCOCFG=/etc/disco
if [ "$NOOP" != "" ]; then
    DISCOROOT=/var/disco/testfs/noop
else
    DISCOROOT=/var/disco/testfs/real
fi

. ${DISCOCFG}/client.cfg

function colorize() {
    sed s/"^info:\(.*\)"/"${COLOR_CYAN}info:\1${COLOR_NORMAL}"/g |\
        sed s/"^warning: \(.*\)"/"${COLOR_YELLOW}warning: \1${COLOR_NORMAL}"/g |\
        sed s/"^error: \(.*\)"/"${COLOR_RED}error: \1${COLOR_NORMAL}"/g |\
        sed s/"^report: \(.*\)"/"${COLOR_CYAN}report: \1${COLOR_NORMAL}"/g
}

function report() {
    if [ "$1" != "" ]; then
	MODULELIST="$1"
    else
	MODULELIST=$(ls /var/disco/reports/)
    fi
    for module in $MODULELIST;
    do
	BASE="report: $module:"
	for file in $(ls /var/disco/reports/${module})
	do
	    echo $BASE $file
	    cat /var/disco/reports/${module}/$file | sed s/"^"/"report:    "/g
	done
    done
}

function dance() {
    mount | grep $DISCOROOT >/dev/null 2>&1
    if [ $? -ne 0 ]; then
	echo "error: disco filesystem does not appear to be mounted, please exec disco-fs-init, disco-fs-mount, and try again."
	exit 1
    fi

    disco-ball fetch_params
    if [ $? -ne 0 ]; then
	echo "error: Unable to fetch parameters for this host from remote server"
	exit 1
    fi

    # Create the toposort of all the modules and fetch all their metadata
    # This also includes fetching modules that aren't explicitly called out in
    # our class list, but are required by 'before' statements in the requires files.
    rm -f /tmp/$$.tsort
    disco-param keys $(hostname)/modules | tac > /tmp/$$.modules.prev
    NEWBALLS=$(cat /tmp/$$.modules.prev)
    while [ "$NEWBALLS" != "" ]; do
	for module in $NEWBALLS
	do
	    NOOP="true" disco-ball fetch $module
	    disco-ball requires $module >> /tmp/$$.tsort
	    cat /tmp/$$.tsort | tsort | tac > /tmp/$$.modules.new
	done
	NEWBALLS=$(diff /tmp/$$.modules.prev /tmp/$$.modules.new | grep "^> " | cut -d " " -f 2-)
	cp /tmp/$$.modules.new /tmp/$$.modules.prev
	if [ "$NEWBALLS" != "" ]; then
	    echo "info: Discovered dependency : ${module} : $(echo -n ${NEWBALLS} | sed s/' '/', '/g)"
	fi
    done

    echo "info: Ready to dance :"
    cat /tmp/$$.tsort | tsort | tac | sed s/"^"/"info:        "/g

#    for module in $(cat /tmp/$$.tsort | tsort | tac)
#    do
#	disco-ball spin ${module}
#    done

    if [ "$REPORT" != "" ]; then
	report
    fi

    #rm -f /tmp/$$.*
}

$1 "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
