#!/usr/bin/perl -w
use strict;
use Getopt::Std;

our $VERSION = ( qw$Revision: 1.3 $ )[-1];
our ($opt_h, $opt_v, $opt_o, $opt_f, $opt_u);

getopts('hvu:f:o:');
usage() if $opt_h;
version() if $opt_v;

die "-u, -f, and -o are required. (Try -h first.)\n"
  unless ($opt_o && $opt_f && $opt_u);

my @objects = get_object_list();

open OUT, ">$opt_o" or die "Cannot open $opt_o: $!\n";
local $" = ', ';
my $time = gmtime;
print OUT  qq{
    -- This file was generated by $0
    -- $time UTC

    REVOKE ALL
    ON     @objects
    FROM   PUBLIC;

    GRANT  ALL
    ON     @objects
    TO     postgres;

    GRANT  SELECT, UPDATE, INSERT, DELETE
    ON     @objects
    TO     $opt_u
};
close OUT;
exit;

################################################################################
# Functions
################################################################################

sub get_object_list {
    my @obj;
	my $state = 'normal';
    open IN, $opt_f or die "Cannot open $opt_f: $!\n";
    while (<IN>) {
	# Skip material that is commented out with C style comments
	$state = 'comment' if /^\s*\/\*/;
	$state = 'normal' if ($state eq 'comment' && /^\s*\*\//);
	next if $state eq 'comment';
	# Skip all but CREATE statments.
	next unless /^CREATE/;
	# Apparently we can't grant permission on indexes or
	# functions so skip them to
	next if /^CREATE.*INDEX/; 
	next if /^CREATE.*FUNCTION/;
	# Remove SQL keywords etc
	s/(^CREATE|TABLE|\s+INDEX|\s+UNIQUE|\s+SEQUENCE|\s+FUNCTION|\(.*$|\s+ON.*$|\s+START.*$)//ig;
	# remove leading and trailing whitespace
	s/(^\s*|\s$)//g;
	push @obj, $_;
    }
    close IN;
    return @obj;
}

sub usage {
    print qq{
Usage: $0

Supported Options:
  Options marked with "*" are required.
* -u User to whome to grant permissions
* -f SQL script to anylise
* -o File to output
  -h Print this usage statement.
  -v Print the version number.

};

exit 0;

}

sub version {
    print "\nBricolage postgres grant generator version $VERSION\n";
    usage();
}

__END__

=pod

=head1 NAME

bric_pggrant

=head1 SYNOPSIS

This script analyzes the PostgreSQL SQL script that creates the Bricolage
database and creates a script granting the correct permissions for each object
CREATED.

=head1 AUTHOR

Mark Jaroski E<lt>mark@geekhive.netE<gt>

=cut

