#!/usr/local/bin/php -n
<?php
// Edit these to match your environment.
// I have separate shares from my XP box of my iTunes and my
// music folders.
$itunes_src  '//RASMUS@192.168.2.105/iTunes';
$itunes_mnt  '/Dell/iTunes';

$music_src   '//RASMUS@192.168.2.105/E';
$music_mnt   '/Dell/e';
$music_path  'iTunes';

$remote_music_path "E:/iTunes/";

$local_itunes '/Users/rasmus/Music/iTunes';
$local_music_path '/Users/rasmus/Music/iTunes/iTunes Music/';

// Don't touch stuff below
$mounts = `mount`;
if(!
preg_match("|\\s$itunes_mnt\\s|",$mounts)) system("mount_smbfs -N $itunes_src $itunes_mnt");
if(!
preg_match("|\\s$music_mnt\\s|"$mounts)) system("mount_smbfs -N $music_src $music_mnt");
$mounts = `mount`;
preg_match("|\\s$itunes_mnt\\s|",$mounts) or die("Unable to mount $itunes_src on $itunes_mnt");
preg_match("|\\s$music_mnt\\s|"$mounts) or die("Unable to mount $music_src on $music_mnt");

$itunes $itunes_mnt '/' $itunes_path;
$music  $music_mnt '/' $music_path;

copy("$local_itunes/iTunes 4 Music Library""$itunes/iTunes 4 Music Library.itl");

$search  str_replace(' ','%20',"file://localhost$local_music_path");
$replace str_replace(' ','%20',"file://localhost/$remote_music_path");

$fp fopen("$local_itunes/iTunes Music Library.xml",'r');
$out fopen("/tmp/new.xml",'w');
while(
$line fgets($fp)) {
    if(
strstr($line,'<key>Music Folder</key>')) {
        
$line "\t<key>Music Folder</key><string>file://localhost/$remote_music_path</string>";
    } else if(
strstr($line$search)) {
        
$line str_replace($search$replace$line);
    }
    
$line rtrim($line)."\r\n";  // unix2dos conversion
    
fwrite($out,$line);    
}
fclose($out);
fclose($fp);
copy("/tmp/new.xml","$itunes/iTunes Music Library.xml");
unlink('/tmp/new.xml');

// My XP box is old and clunky and the clock drifts all the time.  Hence the
// --modify-window of 5 seconds here.  If your clocks are accurate you can get
// rid of that.
system("rsync -avP --modify-window=5 \"$local_music_path\" \"$music_mnt/$music_path\"");
?>