#!/bin/bash
#
# Script to find files that exist in your iTunes Music Library folder that are not
# included in the library. Requires Apple's Developer Tools to be installed since it
# uses FileMerge.app
#
# Usage:
#		./find-missing-music.sh
#
#
# Copyright(c) 2006 Peter A Royal JR. <peter.royal@pobox.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software 
# without restriction, including without limitation the rights to use, copy, modify, 
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 
# permit persons to whom the Software is furnished to do so, subject to the following 
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies 
# or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
# DEALINGS IN THE SOFTWARE.

cat > /tmp/stylesheet <<END
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

	<xsl:output encoding="UTF-8" indent="yes" method="text" />
	
	<xsl:template match="string[preceding-sibling::key = 'Location']">
		<xsl:value-of select="."/><xsl:text>&#10;</xsl:text>
	</xsl:template>
	
	<xsl:template match="text()"/>
</xsl:stylesheet>
END

username=`whoami`                    
music="/Users/$username/Music/iTunes"
                
xsltproc /tmp/stylesheet "$music/iTunes Music Library.xml" | \
egrep "^file" | \
sed -e s/"\%20"/" "/g -e s/"\%5B"/"["/g -e s/"\%5D"/"]"/g -e s/"\%23"/"#"/g -e s/"\%22"/"\""/g -e s/"\%3F"/"?"/g | \
sed -e "s|file://localhost$music/iTunes Music/||" |
sort > /tmp/in_library

find $music/iTunes\ Music -type f | \
grep -v DS_Store | \
sed -e "s|$music/iTunes Music/||" |
sort > /tmp/on_disk

opendiff /tmp/in_library /tmp/on_disk

