#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          stop-bootchart
# Required-Start:    $all
# Required-Stop:
# Should-Start:      
# Default-Start:     1 2 3 4 5
# Default-Stop:
# Short-Description: Stop bootchart
# Description:       Stop bootchart's collector and generate charts from
#                    the results.
### END INIT INFO

[ -x /lib/bootchart/collector ] || exit 0

# Jail we run from in initramfs
JAIL=/dev/.bootchart

# Where we put the output (when run from init)
LOGS=/var/run/bootchart

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

grep -q "profile" /proc/cmdline && exit 0
grep -q "bootchart=disable" /proc/cmdline && exit 0
grep -q "bootchart=[^ ]*nostop" /proc/cmdline && [ -z "$USER" ] && exit 0

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

case "$1" in
    start)
	if [ -d $JAIL ]; then
	    LOGS=$JAIL/log
	elif [ ! -d $LOGS ]; then
	    exit 0
	fi

	# Kill the collector process, wait for it to end
	pkill -f /lib/bootchart/collector
	sleep 2

	# Figure out name for the chart
	base="$(hostname -s)-$(lsb_release -sc)-$(date +%Y%m%d)"
	count=1
	while [ -e "$CHARTS/$base-$count.tgz" -o -e "$CHARTS/$base-$count.png" -o -e "$CHARTS/$base-$count.svg" ]; do
	    count=$(( $count + 1 ))
	done

	BASE="$CHARTS/$base-$count"
	TARBALL="$BASE.tgz"

	# Gather the output into the tarball
	/lib/bootchart/gather "$TARBALL" "$LOGS"

	# Generate SVG and optionally PNG if pybootchartgui is installed
	if [ -x /usr/bin/bootchart ]; then
	    if grep -q "bootchart=svg" /proc/cmdline; then
		format=svg
	    else
		format=png
	    fi

	    bootchart -f $format -o "$CHARTS" "$TARBALL"
	fi

	# Clean up
	rm -rf $LOGS
	if [ -d $JAIL ]; then
	    umount $JAIL/proc
	    rm -rf $JAIL
	fi
	;;
    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
