#! /bin/bash -e

echo "$(date) -- $0 $*" >> /tmp/movieposter.log

# Change this for your environment
SRC_PATH=/var/data/spielfilme
DEFAULT=/etc/movieposter/default.jpg
#DEFAULT=/etc/mediatomb/scripts/unknown-movie-folder.jpg
TARGET_PATH=/var/tmp/spielfilme
DEBUG=1 # set DEBUG to 1 for debugging

# Normally you don't need to change this
SED_FILTER='
   s,.*/,,;                         # remove path
   s/\.[^.]*$//;                    # remove extension
   s/-[^_]*$//;                     # remove after last dash if no _ follows
   s/_[12][90][0-9][0-9]$//;        # remove year at end
   s/^[12][90][0-9][0-9]_//;        # remove year at begin
   s/_*[A-Z][A-Z][A-Z][A-Z]*_*/_/g; # remove word in capitals only
   s/__*/_/g;                       # remove duplicated underscore
   s/_$//;                          # remove trailing whitespaces
   /[a-z]/p;                        # file must contain lowecase letter'
SLEEP=0
IFS="
"

function trace {
    if [ $DEBUG -eq 1 ]; then
        echo "$*" 1>&2
    fi
}

# get poster-link from movie database
function findposterurl {
    # first try OpenMovieDatabase API
    url="http://www.omdbapi.com/?t=$*"
    trace "     $url"
    img=$(wget -q -O- "$url" \
        | sed -n 's/.*Poster":"\([^"]*\)",.*/\1/p');
    if [ -n "$img" -a "$img" != "N/A" ]; then # poster image found
        echo "$img"
        return
    fi
    # then try categories movie and tv in The Movie Database
    # not using the API, because the API requires a key
    for t in movie tv; do
        url="http://www.themoviedb.org/search/$t?query=${*// /+}"
        trace "     $url"
        img=$(wget -q -O- "$url" \
            | html2 2> /dev/null \
            | sed -n '0,/\/@class=poster/d; s/.*\/img\/@src=//p' \
            | head -1)
        if [ -n "$img" -a "$img" != "N/A" ]; then # poster image found
            echo "$img"
            return
        fi
        # make sure there are not too many unsuccessful queries in short time
        sleep $SLEEP # don't want http://www.themoviedb.org to exclude me
    done
}

# try to find poster-link from movie databases in two ways:
# unchanged or by removing the last number
function poster {
    n="$*"
    # try movie name as passed in the arguments
    img=$(findposterurl "$n")
    if [ -z "$img" ]; then
        # try without number at the end or without I at the end
        n2=$(echo "$n" | sed 's/ *[0-9]* *$//; s/ I *$//g')
        if [ "$n2" == "$n" ]; then return; fi # no number at the end
        img=$(findposterurl "$n2")
    fi
    if [ -n "$img" ]; then
        echo "$img";
    fi
}

function getimage {
    f=$(echo "$1" | sed -n "$SED_FILTER")
    if [ -z "$f" ]; then
	trace "**** ingored: $1"
	return
    fi
    n=${f//_/ }; # moviename is filename with spaces instead of underscore
    t="${1%.*}.jpg" # target file name
    if test -n "$TARGET_PATH"; then
	test -d "$TARGET_PATH" || mkdir -p "$TARGET_PATH";
	t="${TARGET_PATH}/${t##*/}"
    fi
    echo "$t"
    if [ -s "$t" ]; then
        trace "**** exists: $t"
        return
    fi # already downloaded
    # try to find movie using full filename
    trace "**** $f -> $n"
    img=$(poster "$n")
    if [ -z "$img" ]; then # no poster found, try with manipulated name
        # split filename at "_-_" and sort by length, search for the parts
        for n2 in $(echo $n | sed 's/ - /\n/g' \
                    | awk '{ print length($0) " " $0; }' | sort -r -n \
                    | cut -d ' ' -f 2-); do 
            if [ "$n" = "$n2" ]; then continue; fi # same - ignore
            trace ",,,, $n -> $n2"
            img=$(poster "$n2")
            if [ -n "$img" ]; then break; fi # found
            for n3 in $(echo $n2 | sed 's/-/\n/g' \
                        | awk '{ print length($0) " " $0; }' | sort -r -n \
                        | cut -d ' ' -f 2-); do # split at -, sort by length
                if [ "$n2" = "$n3" ]; then continue; fi # same - ignore
                echo ".... $n2 -> $n3"
                img=$(poster "$n3")
                if [ -n "$img" ]; then break; fi # found
            done
        done
    fi
    if [ -n "$img" ]; then
        trace "---- Download: $img";
        wget -q -O"$t" $img;
        if ! [ -s "$t" ]; then
            trace "==== ERROR"; rm "$t";
        fi;
    fi;
    if ! [ -s "$t" ]; then
        trace "++++ Transcoding: $1"
	if ! ( ffmpegthumbnailer -i"$1" -o"$t" -f -s400 > /dev/null 2> /dev/null && [ -s "$t" ] ); then
	    trace "++++ Copy Default: $DEFAULT"
	    cp "$DEFAULT" "$t"
	fi
    fi
    if [ -s "$t" ]; then
        trace "++++ INSTALLED!"
    fi
}

function thumbnails() {
    if ! test -f "$1"; then 
	return
    fi
    t="${1%.*}" # target file name                                                                                                  
    if test -n "$TARGET_PATH"; then
        test -d "$TARGET_PATH" || mkdir -p "$TARGET_PATH";
        t="${TARGET_PATH}/${t##*/}"
    fi
    for p in "25%" "50%" "75%"; do
        t2="${t}-${p%\%}.jpg"
	if test -s "$t2"; then
	    continue;
	fi
	trace "++++ Thumbnail: ${t2}"
	if ! ( ffmpegthumbnailer -i"$1" -o"${t2}" -s400 -t"${p}" > /dev/null 2> /dev/null && [ -s "$t2" ] ); then
	    rm "$t2"
	fi
    done
}

#### MAIN #############################################################
while (( "$#" )); do
    arg=$1
    shift
    case "$arg" in
	(-h|--help)
	    cat<<EOF
USAGE

  1) copy image from a movie file:

     $0 in-movie-path out-image-path
  
  2) scan sourcedir and cache images for all files

     $0

  3) other options:

     $0 OPTIONS

OPTIONS

   -h, --help  show this help

EOF
	    exit $#
	    ;;
	(*) 
	    if [ $# -ne 1 ]; then
		echo "**** ERROR! call: $0 --help" 1>&2
		exit 1
	    fi
	    cp $(getimage "$arg") "$1"
	    exit 0
	    ;;
    esac
done

trace "******** $0 ********"
# scan all the movie files and also the directories
# assuming the file name contains the movie title in some predefined way
# find all files and subdirectories take newline as separator
SLEEP=10
for f in $(find $SRC_PATH/ \( -name '*.jpg' -prune \) -o -type f -print); do
    getimage "$f" > /dev/null
    thumbnails "$f"
done
