#!/usr/bin/perl -w

use strict;
use warnings;

while (<STDIN>) {
    chomp;
    if (/\ACOPY (.*?) (\(.*?\)) FROM stdin;\Z/) {
        my $table = $1;
        my $columns = $2;
        $columns =~ s/\"//g;
        while (<STDIN>) {
            chomp;
            last if ($_ eq '\.');
            s/\'/\\'/g;
            if ($table eq 'faqcategories') {
                s/(.*?)\t(.*?)\t(.*?)\t(.*?)\Z/$1\t'$2'\t'$3'\t$4/;
            } elsif ($table eq 'groups') {
                1 while s/\tf\t/\t0\t/;
                1 while s/\tf\Z/\t0/;
                1 while s/\tt\t/\t1\t/;
                1 while s/\tt\Z/\t1/;
                s/\A(.*?)\t(.*?)\t/$1\t'$2'\t/;
            } elsif ($table eq 'faqentries') {
                s/(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\Z/$1\t$2\t'$3'\t'$4'\t$5/;
            } elsif ($table eq 'news') {
                s/(.*?)\t(.*?)\t(.*?)\t(.*?)\Z/$1\t$2\t'$3'\t'$4'/;
            } elsif ($table eq 'oses') {
                s/(.*?)\t(.*?)\t(.*?)\Z/$1\t'$2'\t'$3'/;
            } elsif ($table eq 'projectcategories') {
                s/(.*?)\t(.*?)\t(.*?)\t(.*?)\Z/$1\t$2\t'$3'\t'$4'/;
            } elsif ($table eq 'projects') {
                1 while s/\tf\t/\t0\t/;
                1 while s/\tt\t/\t1\t/;
                s/(.*?\t.*?\t.*?\t.*?)\t(.*?)\t(.*?)\t(.*?)\t/$1\t'$2'\t'$3'\t$4\t/;
                s/(.*?\t.*?\t.*?\t.*?\t.*?\t.*?\t.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\Z/$1\t'$2'\t'$3'\t$4\t'$5'\t'$6'/;
            } elsif ($table eq 'users') {
                1 while s/\tf\t/\t0\t/;
                1 while s/\tt\t/\t1\t/;
                s/(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\Z/$1\t$2\t'$3'\t'$4'\t'$5'\t'$6'\t'$7'/;
            }
            s/\t/,/g;
            print("INSERT INTO $table $columns values ($_);\n");
        }
    }
}

