#!/bin/sh

# Prerequisites
PREREQ=""

# Where we create our jail, this should be on a handy tmpfs, like /dev
JAIL="/dev/.bootchart"


# Output prerequisites for initramfs
prereqs()
{
    echo "$PREREQ"
}

# This function repeatedly runs a command through the boot process and
# stashes its output into a log file for later parsing.
log_output()
{
    local cmd="$1"
    local logfile="$2"
	
    while :; do
	# Write the uptime in jiffies
	sed -e "s/ [0-9].*//;s/\.//" < /proc/uptime
	eval $cmd 2>/dev/null
	echo

	/bin/sleep 0.2
    done >> /log/$logfile
}	

# Spawn off a process to log the various things we want during the boot
# process, these all run in the background so this exits quickly
bottom_half()
{
    log_output "cat /proc/stat" proc_stat.log &
    log_output "cat /proc/diskstats" proc_diskstats.log &
    log_output "cat /proc/*/stat" proc_ps.log &
}

# Make a jail filesystem to live in and run ourselves again with the "bottom"
# argument inside it
make_jail()
{
    mkdir -p $JAIL
    mkdir $JAIL/bin $JAIL/lib
    cp /bin/busybox /bin/sleep $JAIL/bin
    cp /lib/klibc-*.so $JAIL/lib
    cp /scripts/init-top/bootchart $JAIL/bin

    mkdir $JAIL/proc
    mount -t proc none $JAIL/proc
    
    mkdir $JAIL/dev
    mknod $JAIL/dev/null c 1 3
    
    mkdir $JAIL/log
    exec chroot $JAIL /bin/busybox sh /bin/bootchart bottom
}

grep -q "bootchart=disable" /proc/cmdline && exit 0
grep -q "profile" /proc/cmdline && exit 0


case $1 in
    prereqs)
	prereqs
	;;
    bottom)
	bottom_half
	;;
    *)
	make_jail
	;;
esac

exit 0
