#!/usr/bin/perl -w

# modified from mt-load.cgi by Charl P. Botha http://cpbotha.net/
# if you've made the mistake of removing your own author permissions from
# any number of blogs, run this to give yourself full permissions for all
# blogs on the system; just remember to change $SUPER_AUTHOR to the correct
# value...

use strict;

my($SUPER_AUTHOR);
$SUPER_AUTHOR = 'cpbotha';

my($MT_DIR);
BEGIN {
    if ($0 =~ m!(.*[/\\])!) {
        $MT_DIR = $1;
    } else {
        $MT_DIR = './';
    }
    unshift @INC, $MT_DIR . 'lib';
    unshift @INC, $MT_DIR . 'extlib';
}

local $| = 1;

print "Content-Type: text/html\n\n";
print "<pre>\n\n";

use File::Spec;

eval {

my $tmpl_list;
eval { $tmpl_list = require 'MT/default-templates.pl' };
die "Can't find default template list; where is 'default-templates.pl'?\n" .
    "Error: $@\n"
    if $@ || !$tmpl_list || ref($tmpl_list) ne 'ARRAY' || !@$tmpl_list;

print "grantperms.cgi by Charl P. Botha http://cpbotha.net/\n";

require MT;
my $mt = MT->new( Config => $MT_DIR . 'mt.cfg', Directory => $MT_DIR )
    or die MT->errstr;

if ($mt->{cfg}->ObjectDriver eq 'DBI::mysql') {
    my $dbh = MT::Object->driver->{dbh};
    my $schema = File::Spec->catfile($MT_DIR, 'schemas', 'mysql.dump');
    open FH, $schema or die "Can't open schema file '$schema': $!";
    my $ddl;
    { local $/; $ddl = <FH> }
    close FH;
    my @stmts = split /;/, $ddl;
    print "Loading database schema...\n\n";
    for my $stmt (@stmts) {
        $stmt =~ s!^\s*!!;
        $stmt =~ s!\s*$!!;
        next unless $stmt =~ /\S/;
        $dbh->do($stmt) or die $dbh->errstr;
    }
}

require MT::Author;
require MT::Blog;
require MT::Permission;


my $author = MT::Author->load({ name => $SUPER_AUTHOR }) or die "Could not find $SUPER_AUTHOR!\n\n";
print "Author id of $SUPER_AUTHOR is: ", $author->id, "\n";
print "Preparing to grant all permissions to $SUPER_AUTHOR...\n";

# now iterate through all blogs and give this author all permissions
my @blogs = MT::Blog->load;
for my $blog (@blogs) {
    my $perms = MT::Permission->load({ blog_id => $blog->id,
	                               author_id => $author->id });
    if ($perms)
    {
	$perms->set_full_permissions;
	$perms->save and print "All permissions granted for ", $blog->name, "\n" or "Could not grant permissions for ", $blog->name, "\n";
    }
}

}
