cfg
1/14/2015 - 6:40 PM

Hack to enumerate all iTunes backups and write a CSV with the basic information for each backup.

Hack to enumerate all iTunes backups and write a CSV with the basic information for each backup.

#!/usr/local/bin/php
<?php

$plists = array(
	'Manifest.plist' => array(
		// ":Version",
		":WasPasscodeSet",
		":IsEncrypted",
		":Date",
		":Lockdown:ProductType",
		":Lockdown:DeviceName",
		":Lockdown:ProductVersion",
		":Lockdown:SerialNumber",
		":Lockdown:UniqueDeviceID",
	),

	'Status.plist' => array(
		":BackupState",
		":Date",
		":IsFullBackup",
		":SnapshotState",
	),

	'Info.plist' => array(
		":Device Name",
		":Display Name",
		":Last Backup Date",
		":Product Name",
		":Product Type",
		":Product Version",
		":iTunes Version",
	),
);


$base_path = getenv( 'HOME' ) . '/Library/Application Support/MobileSync/Backup';
if( !file_exists( $base_path) ) {
	echo "Aborting; Could not find iTunes backup directory ($base_path)" . PHP_EOL;
	exit( 1 );
}

$plist_buddy = '/usr/libexec/PlistBuddy';
if( !file_exists( $plist_buddy) ) {
	echo 'Aborting; Could not find PlistBuddy' . PHP_EOL;
	exit( 1 );
}


$files = scandir( $base_path );
$backups = array();
$backups['headers'] = array();

foreach( $files as $f ) {
	$path = $base_path . DIRECTORY_SEPARATOR . $f;
	if( is_dir( $path ) ) {
		if( file_exists( $path . DIRECTORY_SEPARATOR . 'Status.plist' )
			&& file_exists( $path . DIRECTORY_SEPARATOR . 'Manifest.plist' )
			&& file_exists( $path . DIRECTORY_SEPARATOR . 'Info.plist' )
		) {
			$backups[$f] = array();
		}
	}
}

$backups['headers'][] = 'Dir';
foreach( $plists as $plist => $keys ) {
	foreach( $keys as $key ) {
		$backups['headers'][] = $key;
	}
}

foreach( $backups as $path => $dummy ) {
	if( $path == 'headers' ) {
		continue;
	}
	$backups[$path][] = $path; // add the backup dir first
	foreach( $plists as $plist => $keys ) {
		foreach( $keys as $key ) {
			$cmd = sprintf( "%s -c \"Print %s\" %s",
				escapeshellcmd( $plist_buddy ),
				escapeshellarg( $key ),
				escapeshellarg( $base_path . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . $plist )
			);
			$val = exec( $cmd, $output, $retval );
			if( $retval != 0 ) {
				$val = "$path/$plist - $key does not exist";
			}
			$backups[$path][] = $val;
		}
	}
}

$set_encoding = function( $value ){
	return iconv('UTF-8', 'Windows-1252', $value);
};

$fp = fopen( $base_path . DIRECTORY_SEPARATOR . 'backups.csv', 'w');
fprintf( $fp, chr( 0xEF ) . chr( 0xBB ) . chr( 0xBF ) ); // write BOM
foreach( $backups as $path => $dummy ) {
	$row = $backups[$path];
	$row = array_map( $set_encoding, $row );
	fputcsv( $fp, $row );
}

fclose($fp);

// EOF