#!/bin/bash

# sunappu_shashin pe 23.4.2010 11.09.56 +0300
#
# Changes since la 27.3.2010 21.51.01 +0200
#	- export LC_LANG prior to calling date
#
# la 27.3.2010 21.51.01 +0200: First release.



test $# -lt 1 && exit 1
test -r "${1}" || exit 1

source "${XDG_CONFIG_HOME:-$HOME/.config/mariginari/sunappu_shashin}" >/dev/null 2>&1 || exit 1
test "x$SNAPSHOTDIR" = "x" && exit 1
test -x "$SNAPSHOTDIR" || exit 1

PATH="$HOME/bin:$PATH"
test -x `which mplayer` || exit 1
test -x `which raberu` || exit 1

VIDEO=`basename "${1}"`
VIDEO=${VIDEO%\.*}
VIDEO=${VIDEO/ /_}
VIDEO=${VIDEO/\"/}

LENGTH=`mplayer -frames 0 -identify "${1}" -vo null -ao null 2>&1 | grep ID_LENGTH | cut -d= -f 2 | cut -d. -f 1`
[[ "$LENGTH" =~ ^[0-9]+$ ]] || exit 1
PICK=$RANDOM
let "PICK %= $LENGTH"

mplayer -ss $PICK -frames 1 -vo png:outdir="$SNAPSHOTDIR" -ao null "${1}" >/dev/null 2>&1

pushd "$SNAPSHOTDIR" >/dev/null 2>&1 || exit 1
SNAPSHOT=`ls -trp | grep -v / | tail -1`

FILMTITLE=`mplayer -frames 1 -vo null -ao null "${1}" 2>&1 | grep -i name | cut -d: -f 2`
FILMTITLE=${FILMTITLE/ /}
FILMTITLE=${FILMTITLE/\"/}
if [ "x$FILMTITLE" == "x" ]
then
	FILMTITLE=$VIDEO
fi
FILMTITLE=$PLAYING$FILMTITLE
export LC_LANG
SNAPSHOTTIME=$(date -d "`stat -c %y "$SNAPSHOT" | cut -d. -f1`" | cut -d+ -f1 | sed 's/[ ]*$//')

convert "$SNAPSHOT" -resize 320x240\! "${SNAPSHOT}" || exit 1
raberu "$SNAPSHOT" "$FILMTITLE" "$SNAPSHOTTIME"
convert "$SNAPSHOT" "${VIDEO}_${PICK}.jpg" || exit 1
rm -f "$SNAPSHOT"
echo "`pwd`/${VIDEO}_${PICK}.jpg"
popd >/dev/null 2>&1 || exit 1