#!/bin/sh
# -------------------------------------------------------------------------
# lsflv - prints a list (and optionally saves copies of) videos currently
# being played by the adobe flash player browser plugin.
#
# Written by John Tsiombikas <nuclear@member.fsf.org>
# This script is placed in the public domain, do whatever you want with it.
# -------------------------------------------------------------------------

mkcopy=no
play=no
player=${PLAYER:-mplayer}
bin=`basename $0`
dir=`pwd`

# if invoked as cpflv always make a copy (as in -c)
if [ "$bin" = cpflv ]; then
	mkcopy=yes
fi

# if invoked as playflv play the video (as in -p)
if [ "$bin" = playflv ]; then
	play=yes
fi

# process arguments
while [ $# -gt 0 ]; do
	case "$1" in
	-c)
		mkcopy=yes
		;;
	-p)
		play=yes
		;;
	-d)
		dir=$2
		shift
		;;
	-h)
		echo "Usage: $bin [options]"
		echo "Options:"
		echo "  -c        make copies of the video files"
		echo "  -d <dir>  change the directory used to copy the files to (default: cwd)"
		echo "  -h        print usage and exit"
		exit 0
		;;
	esac
	shift
done
	

list=`lsof | egrep '(/tmp/Flash|/tmp/mozilla-media-cache)' | awk '{ print $2":"$4 }'`

num=0

for i in $list; do
	pid=`echo $i | awk -F: '{ print $1 }'`
	fd=`echo $i | awk -F: '{ print $2 }' | sed 's/[a-zA-Z]*//g'`

	if [ -n "$fd" ]; then
		path="/proc/$pid/fd/$fd"

		num=`echo "$num + 1" | bc`
		target="$dir/vid$num"

		if [ $mkcopy = yes ]; then
			echo "copy $path -> $target"
			if ! cp $path $target; then
				echo "failed to copy $path to $target" >&2
				exit 1
			fi
		else
			echo "$path"
		fi

		if [ $play = yes ]; then
			$player $path
		fi
	fi
done
