#!/bin/bash

# define programs
XMLSTARLET='./xml'
AWK='gawk'

BEXTENSION=".trailer.mov"

SAVEPATH="./zzztrailertest/"

FEEDURL="./current_720p.xml"

# single-quotes escape everything but other single-quotes.
# you cannot escape a single-quote inside single-quotes
# you have to end the quote, add the single-quote, then restart the quote
# that means that ' turns into '"'"'
# ugly, but less ugly than escaping everything you'd need to inside double-quotes
FILECLEANER_AWK='
{
        ## some html escapes:
        gsub("&gt;",">")
        gsub("&lt;","<")
        gsub("&quot;","\"")
        gsub("&rdquo;","\"")
        gsub("&bdquo;","\"")
        gsub("&lsquo;","\"")
        gsub("&rsquo;","\"")
	gsub("&sbquo;",",")
        gsub("&amp;","\\&")

	## replace fancy "smart" quotes with straight equivalents
        gsub("’","'"'"'")
        gsub("‘","'"'"'")

        gsub("“","\"")
        gsub("”","\"")

        gsub("„","\"")
        gsub("„","\"")

		
	## backquote to apostrophe
	gsub("`","'"'"'")	

	## double quote to apostrophe
        gsub("\"","'"'"'")
		
	## select illegal filename characaters replaced by alternates  (other illegal characters just dropped later)
        gsub(">",")")
        gsub("<","(")
        gsub("[:]"," - ")
        gsub("[/]","-")
		## backslash to dash
	gsub("\\\\","-")

        gsub("[?]","")
        gsub("[|]","-")
        gsub("*","+")
	
        ## double space to single space:
        gsub("  "," ")


        ## sanitize the rest:
        ## gsub("[^- '"'"'[:alnum:] _$+&={}\\[\\]()%@!;,.]*","")

	gsub("^[[:blank:]]*", "")
	gsub("[[:blank:]]*$", "")

        ## dump it to stdout
        print
}
'


# there's a bunch of stuff going on here
# if you define a variable on the same line as a command, it only takes effect for that one command
# if you define a variable using '=(...)', it becomes an array
# $'text' is just like 'text' except some backslash escapes get interpreted, like \n for newline
# IFS makes the field separator be what you set it to instead of any whitespace
# so this is defining an array, one element per line
IFS=$'\n' TRAILERS=(`$XMLSTARLET sel --net -E ascii -D -T -t -m "/records/movieinfo" \
	-v "@id" -o '&#9;' \
	-v "info/title" -o '&#9;' \
	-v "info/postdate" -o '&#9;' \
	-v "preview/large" -o '&#9;' \
	-v "poster/xlarge" --nl \
	$FEEDURL 2>/dev/null`)

# ditto.  hopefully they match
# also, I changed the output encoding to ascii, which seems to work out well
# and I got rid of the indent so that there would be one record per line
IFS=$'\n' movieFields=(`$XMLSTARLET sel --net -E ascii -t -m "/records/movieinfo" \
	-c "." \
	--nl \
	$FEEDURL 2>/dev/null`)

recordDATE=`$XMLSTARLET sel --net -D -T -t -m "/records" \
	-v "@date" \
	$FEEDURL 2>/dev/null`


# I'm not happy with this loop structure
# but having two (hopefully) parallel arrays isn't great either
# and bash only has 1D arrays
# still, it might make more sense to use the array length.
count=-1
for MOVIE in "${TRAILERS[@]}"; do
	# bash (and ksh and zsh) can do math this way
	count=$(($count+1))

	# notice I set the delimiter with an argument instead of in a BEGIN
	MOVIEID=`echo $MOVIE | $AWK -F'\t' '{ print $1 }' 2>/dev/null`

	MOVIETITLE=`echo $MOVIE | $AWK -F'\t' '{ print $2 }' 2>/dev/null`
		# giving the script as an argument instead of a file containing the script
		MOVIETITLEFILE=`echo "$MOVIETITLE" | $AWK "${FILECLEANER_AWK}"`

	POSTDATE=`echo $MOVIE | $AWK -F'\t' '{ print $3 }' 2>/dev/null`

	NEWPREVIEWNAME="${MOVIETITLEFILE}${BEXTENSION}"

	POSTER=`echo $MOVIE | $AWK -F'\t' '{ print $5 }' 2>/dev/null`
		NEWPOSTERNAME="folder.jpg"

	# added braces around the variable names for clarity
	MOVIESAVEPATH="${SAVEPATH}${MOVIETITLEFILE}"

	mkdir -p $MOVIESAVEPATH

	# got rid of an intermediate variable and use the array directly
	echo -e "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<records date=\"$recordDATE\">${movieFields[$count]}</records>" >$MOVIESAVEPATH/temp.xml
done
