#!/bin/sh
# 2010-11-11,12,16,17,12-29	Time-stamp: <2011-02-21 16:05:47 nsmrtks>

set -u

######################################################################
# functions

# usage and exit
# $* = message
usagexit () {
	echo $*

	# ($0 should be the teetime path)
	echo "Usage: $0 [-t tag] command..."

	exit 0
}

# echo wrap
# $* = string to echo
mugi () {
	echo teetime"$*"
}

#
name_try() {
	local nm=$1

	if [ -f "$nm" ]; then
		echo conflicting "$nm" 1>&2
		return 1
	else
		echo "$nm"
		return 0
	fi
}

# generate filename without conflict
# $1 = tag, $2 = suffix (no period)
gename() {
	local tg sx
	tg=$1
	sx=$2

	# 時刻や日付が繰り上がることがあるので、
	# 「以前の失敗した名前に今度は +%H だけを付け加える」
	# などという手法は使えない。

	name_try "$tg"`date +%Y%m%d`."$sx"		&& return 0
	name_try "$tg"`date +%Y%m%d%H`."$sx"		&& return 0
	name_try "$tg"`date +%Y%m%d%H%M`."$sx"		&& return 0
	name_try "$tg"`date +%Y%m%d%H%M%S`."$sx"	&& return 0
	echo sleeping... 1>&2 ; sleep 1
	name_try "$tg"`date +%Y%m%d%H%M%S`."$sx"	&& return 0

	echo giving up 1>&2
	return 1
}

# (There is another way?)
#
# $* = command line
sub () {
	mugi "! `date`"
	mugi "! working directory is `pwd`"
	mugi "> $*"
	eval $*
	mugi "! `date`"
}

######################################################################
# initialize
# - Eat options
# - Set the variable `tag'.
# - If no command is given then exit.

# Eat option and set the variable `tag'.
tag=
while getopts t: arg
do
	case "$arg"
	in
	 t)	tag="$OPTARG" ;;
	 h|?)	usagexit ;;
	esac
done
shift $(($OPTIND - 1))

# If no command is specified then exit.
[ $# -eq 0 ] &&	usagexit "Please spcify command."

# If no tag (-t ..) is specified then set default tag from command arg.
[ -z "$tag" ] && tag=`echo $* | tr '/[:blank:]' '_'`

######################################################################
# run

# set the variable `outfile'
outfile=`gename "$tag" log` || exit 1

# test that we can create a file
#echo -n "Attempting to touch .. "
if touch "$outfile"; then
#	echo " good"
	:
else
	echo "Cannot touch, exiting."
	exit 1
fi

echo "logging (from the next line till the end) to $outfile"

# (do not remember $*)
sub $* 2>&1 | tee "$outfile"

# EoF
