<?php
// $file = dirname( __FILE__ ) . '/backup.sql';
// $file2 = dirname( __FILE__ ) . '/backup-optimized.sql';

// $file = file( $file );

// $sql = ha6OptimizeBackup( $file );
// $sql = join( "\n", $sql );
// file_put_contents( $file2, $resultSql );

function ha6OptimizeBackup( array $file )
{
	// INSERT INTO wp_ha_v5_appointments VALUES (7, 1, 4, 48, 1, 1, 1383887725, 1385440200, 3600, 0, 1800, 1, 0, 'gfLUJCzA', 0, 0);

	$sql = array();
	$inserts = array();
	$deletes = array();

	$re = '/INSERT INTO (.+) VALUES (.+);$/';
	$re2 = '/DELETE FROM wp_users WHERE ID = (\d+);$/';
	$re3 = '/CREATE TABLE IF NOT EXISTS (\w+)/';

	$batchSize = 100;

	$lastTable = NULL;
	foreach( $file as $line ){
		$line = trim( $line );
		if( ! $line ){
			continue;
		}

		if( preg_match($re3, $line, $ma) ){
			$line2 = 'DROP TABLE IF EXISTS ' . $ma[1] . ';';
			$sql[] = $line2;
			$sql[] = $line;
		}
		elseif( preg_match($re2, $line, $ma) ){
			if( ! isset($deletes['wp_users']) ){
				$deletes['wp_users'] = array();
			}
			$deletes['wp_users'][] = $ma[1];
		}
		elseif( preg_match($re, $line, $ma) ){
			$table = $ma[1];

			if( ! isset($inserts[$table]) ){
				if( $lastTable ){
					$values = $inserts[$lastTable];

					$total = count($values);
					for( $i = 0; $i < $total; $i = $i + $batchSize ){
						$thisValues = array_slice( $values, $i, $batchSize );
						$thisValues = join( ',', $thisValues );
						$thisSql = 'INSERT INTO ' . $lastTable . ' VALUES ' . $thisValues;
						$sql[] = $thisSql . ';';
					}
				}

				$inserts[$table] = array();
				$lastTable = $table;
			}
			$inserts[$table][] = $ma[2];
		}
		else {
			$sql[] = $line;
		}
	}

	if( $lastTable ){
		$values = $inserts[$lastTable];

		$total = count( $values );
		for( $i = 0; $i < $total; $i = $i + $batchSize ){
			$thisValues = array_slice( $values, $i, $batchSize );
			$thisValues = join( ',', $thisValues );
			$thisSql = 'INSERT INTO ' . $lastTable . ' VALUES ' . $thisValues;
			$sql[] = $thisSql . ';';
		}
	}

	if( $deletes ){
		foreach( $deletes as $k => $values ){
			$thisSql = 'DELETE FROM ' . $k . ' WHERE ID IN (' . join(',', $values) . ')';
			array_unshift( $sql, $thisSql . ';' );
		}
	}

	return $sql;
}