#!/bin/bash
#Copyright 2000, William Stearns <wstearns@pobox.com>
#See ftp://ftp.stearns.org/pub/apptrace/ or 
#http://www.pobox.com/~wstearns for updates.
#Released under the GPL.
#Requires bash and strace.
#Based on an idea from David S. Miller <davem@redhat.com>:
#	mv /path/to/${PROGRAM} /path/to/${PROGRAM}.ORIG
#	edit /path/to/${PROGRAM}
#	#!/bin/sh
#	strace -f -o /tmp/${PROGRAM}.trace /path/to/${PROGRAM}.ORIG $*
#Thanks, Dave!

case $0 in
*apptrace)
	#User wants to monitor some app, listed as sole command line parameter.
	if [ -f "$1" ]; then
		if [ ! -f "$1.orig" ]; then
			mv -f $1 $1.orig							#Make this script a wrapper around the original app.
			ln -sf $0 $1
		else
			echo $1.orig already exists!  Did you already run $0 $1 ?
			echo No need to run it again, it will continue to work until
			echo explicitly stopped.  To stop this monitoring, use:
			echo mv -f /path/to/some/app/to/monitor.orig /path/to/some/app/to/monitor
		fi
		if ! type -path strace >/dev/null ; then
			echo Please Note!
			echo The \"strace\" program is not present on your system, please install.
		fi
	else
		echo Usage: $0 /path/to/some/app/to/monitor
		echo "    This wrapper script will monitor that application, whether"
		echo called from the command line, inetd, or some other app, and save
		echo time of last run, command line parameters given to the app,
		echo and strace output from running that app in $HOME/apptrace
		echo or /tmp/apptrace .  It will continue to produce this output
		echo every time the app is called until explicitly stopped.  To
		echo stop this monitoring, use:
		echo mv -f /path/to/some/app/to/monitor.orig /path/to/some/app/to/monitor
		echo "    This will not correctly run setuid apps - see the strace"
		echo man page for information on why.
	fi
	;;
*)
	#This app is being called to monitor some other app.
	#Do not echo anything to stdout or stderr.
	if [ -d "$HOME" ]; then								#Make a directory to hold information
		TRACEDIR="$HOME/apptrace"
	else
		TRACEDIR="/tmp/apptrace"
	fi
	if [ ! -d "$TRACEDIR" ]; then
		mkdir --parents $TRACEDIR >/dev/null 2>/dev/null
	fi

	APPNAME=${0##*/}									#Drop all path components
	touch $TRACEDIR/$APPNAME-last-run 2>/dev/null		#Record when it last ran
	echo `date` - $0 $* >>$TRACEDIR/$APPNAME-parameters	#Record command line parameters used ( = $? doesn't work, it probably gets strace's return code)
	if type -path strace >/dev/null ; then
		strace -f -o $TRACEDIR/$APPNAME.$$.trace $0.orig $*	#Save full strace output to a unique file
	else
		echo The \"strace\" program is not present on your system, please install. >$TRACEDIR/$APPNAME.trace
		$0.orig $*
	fi
	;;
esac