#!/bin/sh
#
# Bootchart logger script
# Ziga Mahkovec  <ziga.mahkovec@klika.si>
#
# This script is used for data collection for the bootchart
# boot performance visualization tool (http://www.bootchart.org).
#
# To profile the boot process, bootchartd should be called instead of
# /sbin/init.  Modify the kernel command line to include:
# init=/sbin/bootchartd
#
# bootchartd will then start itself in background and exec /sbin/init
# (or an alternative init process if specified using bootchart_init=)
#
# To profile a running system, run:
# $ /sbin/bootchartd start; sleep 30; /sbin/bootchartd stop
#

# Heavily modified/simplified by W. Batelaan - NXP Semiconductors B.V.

PATH="/sbin:/bin:/usr/sbin:/usr/bin:$PATH"
VERSION="0.8NXP"

# Read configuration.
CONF="/etc/bootchartd.conf"
if [ -f $CONF ]; then
        . $CONF
else
        echo "$CONF missing"
        exit 1
fi

# Start the boot logger.
start()
{
	rm -f "$BOOTLOG_DEST"

	mount -t tmpfs -o size=$TMPFS_SIZE none "$LOG_DIR"
	cd "$LOG_DIR" || return
	rm -f *
	exec >"$BOOTLOG_LOCK" 2>&1
	# Enable process accounting if configured
	if [ "$PROCESS_ACCOUNTING" = "yes" ]; then
		echo >kernel_pacct
		accton kernel_pacct
	fi

	# Wait for /proc to be mounted
	while [ ! -f /proc/stat ]; do $SAMPLE_SLEEP_COMMAND; done
	$SAMPLE_SLEEP_COMMAND

	collect_data &
	wait_a_while &
}

collect_data()
{
	echo >empty
	while [ -f "$BOOTLOG_LOCK" ]; do
		cat /proc/uptime /proc/stat empty >> proc_stat.log
		cat /proc/uptime /proc/[1-9]*/stat empty >> proc_ps.log
		$SAMPLE_SLEEP_COMMAND
	done
	stop
}

# Wait for the boot process to end.
wait_a_while()
{
	sleep "$FIXED_RUN_TIME"
	rm -f "$BOOTLOG_LOCK"
}


# Stop the boot logger.  The lock file is removed to force the loggers in
# background to exit.  Some final log files are created and then all log files
# from the tmpfs are packaged and stored in $BOOTLOG_DEST.
stop()
{
	# Stop process accounting if configured
	local pacct=
	if [ "$PROCESS_ACCOUNTING" = "yes" ]; then
		accton
		pacct=kernel_pacct
	fi

	# Write system information
	log_header

	# Package log files
	tar -zcf "$BOOTLOG_DEST" header $pacct *.log
}


# Log some basic information about the system.
log_header()
{
	(
		echo "version = $VERSION"
		echo "title = Boot chart for $( hostname | sed q ) ($( date ))"
		echo "system.uname = $( uname -srvm | sed q )"
		echo "system.release = NXP"
		echo "system.cpu = $( grep '^cpu' /proc/cpuinfo | sed q ) (1)"
		echo "system.kernel.options = $( sed q /proc/cmdline )"
	) >> header
}

echo "Starting bootchart logging"
trap 'echo "bootchartd: Ignoring HUP"' HUP
start &
