#!/usr/bin/env perl

use strict;
use warnings;
use Data::Stag;

my %relation_type_h = ();
while (@ARGV && $ARGV[0] =~ /^(\-.+)/) {
    my $switch = shift @ARGV;
    if ($switch eq '-t' || $switch eq '--table') {
        while (@ARGV > 1 && $ARGV[0] !~ /^\-/) {
            $relation_type_h{shift @ARGV} = 'table';
        }
    }
    elsif ($switch eq '-v' || $switch eq '--view') {
        while (@ARGV > 1 && $ARGV[0] !~ /^\-/) {
            $relation_type_h{shift @ARGV} = 'view';
        }
    }
    elsif ($switch eq '-h' || $switch eq '--help') {
        print usage();
        exit 0;
    }
    else {
        die "unknown option: $switch";
    }
}
my $f = shift @ARGV;


my $bridge = Data::Stag->parse($f);
my $schema = $bridge->sget('@/schema');

print "CREATE SCHEMA $schema;\n\n";
foreach my $relation ($bridge->get_relation) {
    my $id = $relation->sget('@/id');
    my @indexes = $relation->get_index;
    my $relation_type;

    # anything with indexes is by default a table
    if (@indexes) {
        $relation_type = "table";
    }

    # command line override
    if ($relation_type_h{'ALL'}) {
        $relation_type = 
          $relation_type_h{'ALL'};
    }
    if ($relation_type_h{$id}) {
        $relation_type = 
          $relation_type_h{$id};
    }
    my $sql = $relation->sget_sql;
    $sql =~ s/^\s+//;
    $sql =~ s/\;\s*//;
    printf("CREATE %s %s.%s AS\n%s;\n",
           uc($relation_type), 
           $schema,
           $id,
           $sql);
    print "$_\n" foreach @indexes;
    print "\n\n";
}

exit 0;

# --

sub usage {
    return <<EOM
create-bridge-sql.pl [OPTIONS] bridge.sql.xml > bridge.sql      
Options:
  -t --table : list of relations to be materialized
  -v --view  : list of relations to be unmaterialized
ALL can be used to specify a default

Examples:
create-bridge-sql.pl -v term term2term godb-bridge.sql.xml > godb-bridge.sql      
create-bridge-sql.pl -v ALL -t term godb-bridge.sql.xml > godb-bridge.sql      

TODO:
Currently the autogenerated bridge can only be applied once.
It would be nice (and easy) to have code to arbitrarily switch
between tables and views at any points in the database lifecycle

Also - finer grained control over indexes
EOM
      ;
}
