#!/usr/bin/perl

#require perl5.10;

use warnings;
use strict;

my $temp = '';
while (<>) {
    # only add "" if we actually need them
    s/\[([^]]+)\]/$1 =~ m{\W}?qq("$1"):$1/eg;
    s/^\s*GO$/;/;
    s/tinyint/smallint/;
    s/binary(?:\s*\([^)]+\))?/bytea/ig;
    s/smalldatetime/TIMESTAMP/ig;
    s/DATETIME/TIMESTAMP/ig;
    s/(?:NON)?CLUSTERED\s*//g;
    s/\s*ASC\s*//g;
    s/int\s*IDENTITY\s*\(\d+,\s*\d+\)/SERIAL/ig;
    # mssql uses stupid names for indexes apparently; ditch them and
    # let pgsql choose
    s/(CREATE\s+(?:UNIQUE\s+)?INDEX\s+)\S+\s+(ON\s+)/$1$2/gi;
    # set defaults properly
#    use re 'debug';
    s/(?<altertable>ALTER\s+TABLE\s+\S+) # table name
      \s+ADD\s+CONSTRAINT\s+
      \S+\s+DEFAULT\s+
      (?<function>\((?<unbraceddef>(?:[^\(\)]++|(?&function))*)\)) # default value
      \s+FOR\s+
      (?<column>\S+) # column
      /$+{altertable} ALTER COLUMN $+{column} SET DEFAULT $+{unbraceddef};/gix;
    s/GETDATE\(\)/NOW()/gix;
    $temp .= $_;
}
$temp =~ s/\r//g;

# cleanup \n; madness
$temp =~ s/\n(;)/$1/g;
$temp =~ s/\n\n+/\n/g;
print $temp;
