#!/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
    for module in $(disco-param keys $(hostname)/modules)
    do
	NOOP="true" disco-ball fetch $module
	disco-ball requires $module >> /tmp/$$.tsort
    done

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

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

}

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