#!/usr/bin/perl

use warnings;
use strict;

sub print_pre {
 my $fh = shift;
 my $to_print = <<EOL;
/*!40101 SET NAMES utf8 */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET UNIQUE_CHECKS=0 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET SQL_NOTES=0 */;

EOL
 print $fh $to_print;
}

my $dump_fh;
if (@ARGV) {
  my $dump_file = shift;
  open $dump_fh, '<', $dump_file or die $!;
}
else {
  $dump_fh = *STDIN
}

my $current_create_db_stmt;
my $current_use_db_stmt;
my $current_n = 0;
my $out_fh;
while (<$dump_fh>) {
  if (/^CREATE DATABASE/) {
    $current_create_db_stmt = $_;
  }
  elsif (/^USE/) {
    $current_use_db_stmt = $_;
  }
  elsif (/^DROP TABLE IF EXISTS `(.+)`;/) {
    my $table = $1;
    my $pretty_n = sprintf("%04d", $current_n++);
    if ($out_fh) {
      close $out_fh;
    }
    open $out_fh, '>', "$pretty_n-$table" or die $!;
    print_pre $out_fh;
    print $out_fh $current_create_db_stmt;
    print $out_fh $current_use_db_stmt;
  }
  print $out_fh $_ if $out_fh;
}

close $out_fh;



