#!/bin/bash
#
# moviedbgenerator			Development:	Mid 2005 till now
#					Last Modified:	31-12-2007
#
# 31-12| ZOMG w/ symlinker in place it should work for unlimited
# 2007 | amount of directories! I should remove the DIR1/DIR2 stuff 
# note | some day...
#
# (GPL) Marno van der Molen - marno.vandermolen@gmail.com
#
# New in 1.5.1
# ------------ 
#
# - Full Rating Database support! (See -r option)
#   o You can add a rating for one specific movie (-r "moviename")
#   o You can add ratings for all movies (-r)
# - Loads of bugfixes! The script should *never* fail without
#   giving a reason why it failed.
# - Some cosmetic changes and fixes
#
# About
# -----
#
# Generates a list of movies in the directory's you provide, and outputs a list
# with corresponding imdb-information.
# - Does not recurse into subdirectories.
# - Movies have to use proper naming (Species III instead of
#   Species.III.Diamond-XviD for example. It has to be the IMDB name.)
# - If you do not want something to be indexed, simply do
#   'touch <directory you dont want to be indexed>/.noindex' and the script
#   will not index that directory.
#
# Usage
# -----
#
# ./movielistgenerator.sh -V to display the version/credits
# ./movielistgenerator.sh -v to display verbose messages. This is the
#                            recommended way of running the script.
#
# You might not need to run the script as root for your setup. I force it to
# only run as root cause I have it write out a file to my webserver space, for
# which it requires root privilegs. You can remove the 'privilege check' below
# if you don't want to use the root check.
#
# It is advised to review the Program Variables listing, cause you probably
# want to modify those to suit your setup.
#
# Requirements
# ------------
#
#	The following programs need to be in your path:
#	- cp / rm / mv / du / ls
#	- this script has only been tested in a BASH environment, but should
#         work in SH or other shells as well.
#
# Example can be seen here: http://marno.homelinux.com/moviedb/ (this has taken offline)
#
# GPL - Marno van der Molen. marno.vandermolen@gmail.com. http://marno.homelinux.com
#
# You can use this script free of charge, but please give proper credit where due!
# Also, if you use this; please send me a mail :-)
#

# Shell variables, do not change!
GREEN="\033[1;32m"
RED="\033[0;31m"
GRAY="\033[0;37m"
WHITE="\033[1;37m"
VERBOSE=0
FILE_VERSION=1.5.1
RATING_DONE=1

# Options verification, do not change!
if [ "$#" = "1" -o "$#" = "2" ]
then
	if [ "$1" = "-f"  ]
	then
		if [ "$2" = "" ]
		then
			echo -e "${WHITE}Missing argument. The option -f needs an argument.${GRAY}"
			exit
		else
		FILE=$2
		#VALID=1
		FROM_FILE=1
		fi
	elif [ "$1" = "-v" ]
	then
		#VALID=1
		VERBOSE=2
	elif [ "$1" = "-vv" ]
	then
		#VALID=1
		VERBOSE=1
	elif [ "$1" = "-V" ]
	then
		#VALID=1
		VERSION=1
	elif [ "$1" = "-h" -o "$1" = "-H" ]
	then
	echo -e "Help:

Available arguments are:
-v          Generate Marno's DB and show stats
-vv         Generate Marno's DB very verbose.
-V          Show Version info
-f <file>   Read the directory listing from a text file.
-m          Generate Marno's DB (From directory structure).
            This method shows the least info/stats.
-r          This method runs the dbgenerator in RATING-mode
-r <movie>  This method runs the dbgenerator in RATING-mode for the given movie
            
Only one argument is allowed, except for -f.

For more advanced configuration options, open ${WHITE}$0${GRAY}
in a text editor, and change some variables.

GPL - Marno van der Molen 2005"
exit
	elif [ "$1" = "-r" ]
	then
		DO_RATING=1
		ADD_MOVIE=$2
		RATING_DONE=0
		#VALID=1
	elif [ "$1" = "-m" -o "$DO_RATING" = "1" ]
	then
		FROM_DIRS=1
		#VALID=1
	else #if [ "$VALID" != "1" ]
		echo -e "${WHITE}Unknown option! Run $0 -h for help.$GRAY"
		exit
	fi
else
	echo -e "${WHITE}Wrong amount of options! You have to tell me what to do.$GRAY"
	exit
fi

# Privilege check (Remove the next 5 lines if you want to run this as a regular user)
if [ `whoami` != "root" ]
then
	echo "You do not appear to have sufficient privileges."
	exit
fi

# Check whether the user requests the program version
if [ "$VERSION" = "1" ]
then
	echo -e "$WHITE
	Movielist generator version ${FILE_VERSION}
	
	This script is GPL. Use it as you see fit,
	but give credit where due.
	
	This script has been developed by:
	$GREEN
	      Marno van der Molen
	$WHITE
	- marno.vandermolen@gmail.com
	- http://marno.homelinux.com
	
	Credit goes to linuxquestions.org for helping
	me out with some nasty coding problems. $GRAY"
	exit
fi

# Update the virtual movie directory to contain all the movies from all the dirs.
# This is probably only usefull on my server
# sh /etc/cron.hourly/symlinks
sh /usr/bin/update-symlinks

if [ $VERBOSE = 1 ]; then
				echo -ne "$WHITE 1. Assigning variables... ${GRAY}"
elif [ "$1" = "-r" ]; then
				echo "" > /dev/null 2>&1
elif [ $1 != "-f" ]; then
				echo -ne "$WHITE Generating moviedatabase... $GRAY"
else
				echo -ne "$WHITE 1. Assigning variables... ${GRAY}"
fi
# Program Variables (Change this!!)
EXCLUDE=.noindex		# Name of the file you wish to use as 'noindex'
OUTPUT=/home/httpd/html/moviedb # Directory you wish to put the LIST in
LIST=/movielist.htm		# Name of the LIST
TMP=/tmp/templist.tmp		# Name of temp file (usually in /tmp/something)
TMPnew=/tmp/newlist.tmp		# Second temp file, do not use the same temp file for two variables!
TMPsize=/tmp/sizelist.tmp	# Thirth temp file (sorry for the tmp spam)
SITENAME="Marno's Homepage"	# Sets the website name to output into html file.
STYLE=/style.css		# If you use a stylesheet, set this to the webserver path to it.
DATE=`date +%b`			# Don't change this!
DIR=/largedisk/shares/movies
#DIR1=/megadisk/movies		# Dont use trailing /
#DIR2=/home/movies		# If you don't have 4 dirs, you need to remove
#DIR3=/bigdisk/movies		# the corresponding code refering to it, too. This
#DIR4=/largedisk/movies		# is not hard to do. Lines refering to dirs are 250, 375 (the 'sed' commands refer to it)
EMPTYCOUNT=0			# Initialize it as 0 	(DONT CHANGE)
NEWCOUNT=0			# ..			(DONT CHANGE)
TOTALCOUNT=0			# ..			(DONT CHANGE)
NAMEFILE=.namefile		# The filename you wish to use in the moviedir to specify alternate name to display (& search for)
RATINGFILE=/etc/movieratings	# The file you wish to store your ratings in
TOTALSIZE=`du -lhsc $DIR | awk {' print $1 '} | sed s/[A-Z]//g | tail -n 1`

# Marno 07/09/09
# WTF does this block of code do?????
#
if [ "$1" = "-f" ]
then
	FILE=$2
	OUTPUT=/home/httpd/html/wesleydb
	SITENAME="Wesley's DB"
	LIST=/movielist.htm
fi
#
# ???????????????????????????????????

# DO NOT CHANGE BELOW THIS LINE
################################### SCRIPT ###################################
temp_var=$IFS
IFS="
"

# Remove temp files without warning
rm $TMP > /dev/null 2>&1
rm $TMPnew > /dev/null 2>&1
rm $TMPsize > /dev/null 2>&1

if [ "$1" = "-f" ]
then
	echo -e "${WHITE}done.${GRAY}"
	echo -e "$WHITE 2. Now Indexing movies... ($FILE)${GRAY}"
for MOVIEPATH in `cat $FILE` # | sed -e 's/\ /\\ /g'` # -e 's/.*/"&"/g'
do
	#
	# Within this for-loop, $MOVIE defines the movie and we can write it out one bye one.
	#
	MOVIE=`echo $MOVIEPATH | awk {'print $9" "$10" "$11" "$12" "$13" "$14'} | sed 's/\ /\\ /g'`
	echo "<li><!--<f class=orange>-->$MOVIE</f> <<a href=\"http://www.google.nl/search?hl=nl&q=site:imdb.com &#34 $MOVIE&#34&btnI=Ik+doe+een+gok&meta=\"/ target="imdb">I</a>|<a href=\"http://www.google.nl/search?hl=nl&q=site:movies.yahoo.com &#34 $MOVIE&#34&btnI=Ik+doe+een+gok&meta=\" target="imdb">Y</a>></li>" >> $TMP
	mkdir "/tmp/$MOVIE"
	echo "<h1>$MOVIE</h1>" >> "/tmp/$MOVIE/index.htm"
	wget "http://www.google.nl/search?hl=nl&q=site:imdb.com &#34 $MOVIE&#34 &btnI=Ik+doe+een+gok&meta=\""
done

echo -e "\n $WHITE  Indexing done!\n${GRAY}"

# Write out some nice HTML / title / stylesheet etc + sort the damn listing...
	echo -ne "$WHITE 3. Now sorting the movielist... "

echo "<html><head><title>$SITENAME :: Server Movie Listing</title><link rel=stylesheet type=text/css href=$STYLE></head><body class=simple><br>- There are `cat $TMP -n | awk {' print $1 '} | tail -n 1` movies in this database.<br>- Database Generation Date: `date +%b\ %d\,\ %H\:%M`.<br>- Cannot determine size from input file!<br>- Generated from input file: $FILE<br><br>(I = IMDB, Y = Yahoo Movies)<hr>" >> $TMP
echo '<!--ZZZ--><br><a href="/moviedb/imdb.php" target="imdb">Back to opening screen.</a><br>' >> $TMP
sort -df $TMP > $OUTPUT/$LIST
rm $TMP > /dev/null 2>&1

				echo -e "${WHITE}done. $GRAY"
				echo -e "$WHITE 4. File has been made available online.$GRAY"

else

if [ $VERBOSE = 1 ]; then
	echo -e "${WHITE}done.${GRAY}"
	echo -e "$WHITE 2. Now Indexing movies... ${GRAY}"
	echo -e "${WHITE}\n   Excluding the following movies: ${GRAY}"
fi

for MOVIEPATH in `ls -d $DIR/* --color=no | sed -e 's/\ /\\ /g'` # -e 's/.*/"&"/g'
do
# Within this for-loop, $MOVIE defines the movie and we can write it out one bye one.

	MOVIE=`echo $MOVIEPATH | sed -e s#$DIR1/##g -e s#$DIR2/##g -e s#$DIR3/##g -e s#$DIR4/##g`
	
	if [ -f $MOVIEPATH/$EXCLUDE ]
	then
		if [ $VERBOSE = 1 ]; then
		echo "   - $MOVIE"
		fi
	else
		SIZE="`du -lhs $MOVIEPATH | awk {'print $1'}`"

		if [ -f $MOVIEPATH/$NAMEFILE ]
		then
			FULLMOVIE=$MOVIE
			MOVIE=`cat $MOVIEPATH/$NAMEFILE`
		fi
		
		if [ `cat $RATINGFILE | grep $MOVIE > /dev/null; echo $?` = 1 ]
		then
			RATING="?"
			# Movie has no rating
			if [ "$DO_RATING" = "1" ]
			then
				if [ -z "$ADD_MOVIE" ]
				then
					echo -ne "Rating for ${WHITE}\"$MOVIE\": ${GRAY}"
					read RATING
	
					if [ "$RATING" = "" -o "$RATING" = "?" ]
					then
						echo "" > /dev/null 2>&1
					else
						# Write it out
						echo -e "$MOVIE\n$RATING" >> $RATINGFILE
					fi
				else
					if [ "$MOVIE" = "$ADD_MOVIE" ]
					then
						RATING_DONE=SUCCES
						echo -ne "Rating for ${WHITE}\"$MOVIE\":${GRAY} "
						read RATING
						
						if [ "$RATING" = "" -o "$RATING" = "?" ]
						then
							RATING=ERROR
						else
							#Write it out
							echo -e "$MOVIE\n$RATING" >> $RATINGFILE
							#exit
						fi
					fi				
				fi
			fi
		else
			# Movie has a rating
			RATING=`cat $RATINGFILE | grep $MOVIE -A 1 | tail -n 1`
		fi
		
		if [ $SIZE = 0 ]
		then
			SIZE=""
			EMPTYCOUNT=$(($EMPTYCOUNT+1))
			TOTALCOUNT=$(($TOTALCOUNT+1))
			echo "   - $MOVIE" >> $TMPsize
		else
			SIZE="($SIZE)"
		fi

		if [ `ls -aldtQ --time-style="locale" $MOVIEPATH | awk {' print $6 '}` = $DATE ]
		then
			NEWCOUNT=$(($NEWCOUNT+1))
			TOTALCOUNT=$(($TOTALCOUNT+1))
			echo "   - $MOVIE" >> $TMPnew
			MARKOPEN="<!--<b class=\"orange\">-->"
			MARKCLOSE="<!--</b>-->"
			#MARKOPEN="<b class=\"orange\">"
			#MARKCLOSE="</b>"
		else
			TOTALCOUNT=$(($TOTALCOUNT+1))
			MARKOPEN="<!--<b class=\"orange\">-->"
			MARKCLOSE="<!--</b>-->"
		fi
		# Write it out! NOW!	
		echo "<li>${MARKOPEN}$MOVIE${MARKCLOSE} <a href=\"http://www.google.nl/search?hl=nl&q=site:imdb.com &#34 $MOVIE&#34&btnI=Ik+doe+een+gok&meta=\"/ target="imdb">I</a>|<a href=\"http://www.google.nl/search?hl=nl&q=site:movies.yahoo.com &#34 $MOVIE&#34&btnI=Ik+doe+een+gok&meta=\" target="imdb">Y</a> $SIZE <b class=\"rating\">($RATING)</b></li>" >> $TMP
	fi
done

## Check rating
if [ "$DO_RATING" = "1" ]
then
	if [ -z "$ADD_MOVIE" ]
	then
		echo "" > /dev/null 2>&1
	else

		if [ "$RATING_DONE" = "SUCCES" ]
		then
			echo -e "Movierating for ${WHITE}\"$ADD_MOVIE\"${GRAY} succesfully added!"
			echo -n "Update moviedb now? [y/N]: "
			read ANSWER
			if [ "$ANSWER" = "Y" -o "$ANSWER" = "y" ]
			then
				echo -n "Updating now..."
				moviedbgenerator -m > /dev/null 2>&1
				echo " done."
			fi
			exit
		else
			echo -e "Rating for ${WHITE}\"$ADD_MOVIE\"${GRAY} allready exists or movie not found!"
			exit
		fi
	fi
fi

if [ $VERBOSE = 1 ]; then
	if [ -f $TMPnew ]
	then
		echo -e "\n $WHITE  These movies have been marked as new: $GRAY"
		cat $TMPnew
		rm $TMPnew > /dev/null2>&1
	fi
	
	if [ -f $TMPsize ]
	then
		echo -e "\n $WHITE  These movies were 0Kb in size: $GRAY"
		cat $TMPsize
		rm $TMPsize > /dev/null2>&1
	fi
fi

if [ $VERBOSE = 1 ]; then
echo -e "\n $WHITE  Indexing done!\n${GRAY}"
fi

# Write out some nice HTML / title / stylesheet etc + sort the damn listing...
if [ $VERBOSE = 1 ]; then
	echo -ne "$WHITE 3. Now sorting the movielist... "
fi

echo "<!--AAA--><html><head><title>$SITENAME :: Server Movie Listing</title><link rel=stylesheet type=text/css href=$STYLE></head><body class=simple>- Total movie database size is <b class=\"green\">${TOTALSIZE}GB.</b><br>- There are <b class=\"green\">$TOTALCOUNT movies</b> in this database.<br>- Database Generation Date: `date +%b\ %d\,\ %H\:%M`.<br><!-- - New movies this month: <b class=\"green\">$NEWCOUNT</b>.--><br><br>(I = IMDB, Y = Yahoo Movies)<hr>" >> $TMP
echo '<!--ZZZ--><br><a href="/moviedb/imdb.php" target="imdb">Back to opening screen.</a><br>' >> $TMP
sort -df $TMP > $OUTPUT/$LIST
rm $TMP > /dev/null 2>&1

if [ "$DO_RATING" = "1" ]
then
	echo "" > /dev/null 2>&1	
else
	if [ $VERBOSE = 1 ]; then
				echo -e "${WHITE}done.${GRAY}"
				echo -e "$WHITE 4. File has been made available online.$GRAY"
	elif [ $VERBOSE = 2 ]; then
				echo -e "${WHITE}done.${GRAY}"
				echo -e "\n${WHITE} - Total Movies: $TOTALCOUNT\n - Total New: $NEWCOUNT\n - Total Size: ${TOTALSIZE}GB\n$GRAY"
				echo -e "$WHITE File has been made available online.$GRAY"
	else
				echo -e "${WHITE}done.${GRAY}"
	fi
fi
fi

IFS=${temp_var}

# EOF
