#!/bin/bash -e
[ $# -lt 1 ] && echo "$0 [-f|--force] wmv[asf]file(s)" && exit 1

LANG=C
PATH=${PATH}:/usr/local/bin

exitproc(){ rm -rf "${TEMPFILE}" "${TEMPLNK1}" "${TEMPLNK2}";}

trap '
exitproc
exit 1
' 2 15

FORCE=false
while test -n "${1}"
do
case "${1}" in
-f|--force)FORCE=true;
echo "Force option was specified."
shift;;
*)break;;
esac
done


while test -n "${1}"
do

starttime=`date +%s`
PLACE="`dirname "${1}"`"
TARGETFILE=${1}
TARGETEXT=${TARGETFILE##*\.}
basename=${TARGETFILE%\.*}
WMA="${basename}.wma"
MODTIME=`stat -c %y "${TARGETFILE}"|sed 's/\-/\//g'|cut -b1-19`

if ! test -f "${TARGETFILE}"; then
echo "Error, ${TARGETFILE} not found." >&2
shift
continue
fi

while true
do
case "${TARGETEXT}" in
wmv|WMV|asf|ASF)break;;
*)
echo "Warning, ${TARGETFILE} is not a wmv file." >&2
shift
continue 2
break;;
esac
done

left1char="${TARGETFILE:0:1}"
if test "${left1char}" != "/"; then
TARGETFILE="`pwd`/${TARGETFILE}"
PLACE="`pwd`/${PLACE}"
fi


# (asfbinコマンドは7bitパスしか許容しない為にリンクを使用)
export TMPDIR=/tmp
TEMPLNK1="`mktemp`"
ln -sf "${TARGETFILE}" "${TEMPLNK1}"
StreamNum=$(asfbin -infohdr -i "${TEMPLNK1}"|grep "Stream \[.\]:"|wc -l)
VideoStreamNum=$(asfbin -infohdr -i "${TEMPLNK1}"|grep "Stream \[.\]:"|grep -v "Stream \[.\]: Audio"|wc -l)

if test ${StreamNum} -eq ${VideoStreamNum}; then
	rm "${TEMPLNK1}"
	echo "Warning, ${TARGETFILE} does not contain Audio Stream." >&2
	shift
	continue
elif test ${VideoStreamNum} -ge 1; then
	if $FORCE; then
		:
	elif test -e "${WMA}"; then
		rm "${TEMPLNK1}"
		echo "Warning, ${WMA} already exists." >&2
		shift
		continue
	else
		:
	fi

	echo "-------------------------------------------------"
	echo "${TARGETFILE}"
	export TMPDIR="${PLACE}"
	TEMPFILE="`mktemp`"
	export TMPDIR=/tmp
	TEMPLNK2="`mktemp`"
	ln -sf "${TEMPFILE}" "${TEMPLNK2}"

	str=
	for ((i=1;i<=$VideoStreamNum;i++))
	do
	line="$(asfbin -infohdr -i "${TEMPLNK1}"|grep "Stream \[.\]:"|grep -v "Stream \[.\]: Audio"|head -${i}|tail -1)"
	line=${line#*Stream \[*}  # 最初のStream [より後ろの文字列を取り出す
	line=${line%%\]*}  # 最初の]より前の文字列を取り出す   
	str=${str}" ${line}"
	done

	asfbin -y -nostr${str} -i "${TEMPLNK1}" -o "${TEMPLNK2}" && \
	mv "${TEMPFILE}" "${WMA}"
	rm "${TEMPLNK2}"

else
	rm "${TEMPLNK1}"
	echo "Error, ${TARGETFILE} is not a suitable file." >&2
	shift
	continue
fi
rm "${TEMPLNK1}"

chmod go+r "${WMA}"
endtime=`date +%s`
elapsed=`expr $endtime - $starttime`
#touch -t `date -d "$MODTIME $elapsed seconds" "+%Y%m%d%H%M.%S"` "${WMA}"
touch -t `date -d "$MODTIME" "+%Y%m%d%H%M.%S"` "${WMA}"
echo "Extracting: Done."

shift
done
