#!/bin/sh -e

# Version of bootchart
VERSION="0.8+20051109-ubuntu"

# Where the jail created in initramfs appears on our filesystem,
# usually the same place unless you're being odd
JAIL="/dev/.bootchart"

# Where we drop the tarball
TARBALL="/var/log/bootchart.tgz"

# Where we drop charts
CHARTS="/var/log/bootchart"


test -d $JAIL || exit 0


# Get lsb functions
. /lib/lsb/init-functions
. /etc/default/rcS


# Kill any bootchart processes that are still running
stop_bootchart()
{
    pids=$(ps ax | awk '/bootchart bottom/ {print $1}')
    [ -n "$pids" ] || return

    kill $pids 2>/dev/null || true
    sleep 2
}

# Output the header file with information about the system, as this stuff
# almost certainly wasn't available in the jail
header()
{
    echo "version = $VERSION"
    echo "title = Boot chart for $(hostname) ($(date))"
    echo "system.uname = $(uname -srvm)"
    echo "system.release = $(lsb_release -sd)"
    echo "system.cpu = $(grep '^model name' /proc/cpuinfo)"\
	"($(grep -c '^model name' /proc/cpuinfo))"
    echo "system.kernel.options = $(sed q /proc/cmdline)"
}

# Create a tarball of the logs and header which can be parsed into the chart
create_tarball()
{
    (cd $JAIL/log && tar czf $TARBALL header *.log)
}

# Clean up the jail
clean_jail()
{
    umount $JAIL/proc
    rm -rf $JAIL
}

# Process the tarball and create a png chart
create_chart()
{
    base="$(lsb_release -sc)-$(date +%Y%m%d)"
    count=1
    while [ -e "$CHARTS/$base-$count.png" ]; do
	count=$(( $count + 1 ))
    done

    /usr/bin/java -jar /usr/share/bootchart/bootchart.jar \
	-o $CHARTS -f svg > /dev/null
    rsvg $CHARTS/bootchart.svgz $CHARTS/$base-$count.png
    rm -f $CHARTS/bootchart.svgz
    rm -f $TARBALL
}

upload_chart()
{
    for item in $(cat /proc/cmdline); do
        case $item in
            bootchart=*)
                boottype=$(echo "$item" | awk -F, '{print $2}')
                ;;
        esac
    done
    wget -O /dev/null -q --post-file $CHARTS/$base-$count.png http://bootchart.err.no/upload/$(lsb_release -si)/$(lsb_release -sc)/$(uname -r)/$(uname -m)/$boottype
}

case "$1" in
    start)
	stop_bootchart
	header > $JAIL/log/header
	create_tarball
	clean_jail
	create_chart
        grep -q bootchart=upload /proc/cmdline && upload_chart
	;;
    stop|restart|reload|force-reload)
	;;
    *)
	log_success_msg "Usage: /etc/init.d/bootchart-stop {start|stop|restart|reload|force-reload}"
	exit 1
esac

exit 0
